[x86] Stop shuffling zero vectors. =]
[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 "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/VariadicFunction.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 static cl::opt<bool> ExperimentalVectorShuffleLowering(
71     "x86-experimental-vector-shuffle-lowering", cl::init(true),
72     cl::desc("Enable an experimental vector shuffle lowering code path."),
73     cl::Hidden);
74
75 static cl::opt<bool> ExperimentalVectorShuffleLegality(
76     "x86-experimental-vector-shuffle-legality", cl::init(false),
77     cl::desc("Enable experimental shuffle legality based on the experimental "
78              "shuffle lowering. Should only be used with the experimental "
79              "shuffle lowering."),
80     cl::Hidden);
81
82 static cl::opt<int> ReciprocalEstimateRefinementSteps(
83     "x86-recip-refinement-steps", cl::init(1),
84     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
85              "result of the hardware reciprocal estimate instruction."),
86     cl::NotHidden);
87
88 // Forward declarations.
89 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
90                        SDValue V2);
91
92 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
93                                 SelectionDAG &DAG, SDLoc dl,
94                                 unsigned vectorWidth) {
95   assert((vectorWidth == 128 || vectorWidth == 256) &&
96          "Unsupported vector width");
97   EVT VT = Vec.getValueType();
98   EVT ElVT = VT.getVectorElementType();
99   unsigned Factor = VT.getSizeInBits()/vectorWidth;
100   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
101                                   VT.getVectorNumElements()/Factor);
102
103   // Extract from UNDEF is UNDEF.
104   if (Vec.getOpcode() == ISD::UNDEF)
105     return DAG.getUNDEF(ResultVT);
106
107   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
108   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
109
110   // This is the index of the first element of the vectorWidth-bit chunk
111   // we want.
112   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
113                                * ElemsPerChunk);
114
115   // If the input is a buildvector just emit a smaller one.
116   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
117     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
118                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
119                                     ElemsPerChunk));
120
121   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
123 }
124
125 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
126 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
127 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
128 /// instructions or a simple subregister reference. Idx is an index in the
129 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
130 /// lowering EXTRACT_VECTOR_ELT operations easier.
131 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
132                                    SelectionDAG &DAG, SDLoc dl) {
133   assert((Vec.getValueType().is256BitVector() ||
134           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
135   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
136 }
137
138 /// Generate a DAG to grab 256-bits from a 512-bit vector.
139 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
140                                    SelectionDAG &DAG, SDLoc dl) {
141   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
142   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
143 }
144
145 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
146                                unsigned IdxVal, SelectionDAG &DAG,
147                                SDLoc dl, unsigned vectorWidth) {
148   assert((vectorWidth == 128 || vectorWidth == 256) &&
149          "Unsupported vector width");
150   // Inserting UNDEF is Result
151   if (Vec.getOpcode() == ISD::UNDEF)
152     return Result;
153   EVT VT = Vec.getValueType();
154   EVT ElVT = VT.getVectorElementType();
155   EVT ResultVT = Result.getValueType();
156
157   // Insert the relevant vectorWidth bits.
158   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
159
160   // This is the index of the first element of the vectorWidth-bit chunk
161   // we want.
162   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
163                                * ElemsPerChunk);
164
165   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
166   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
167 }
168
169 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
170 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
171 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
172 /// simple superregister reference.  Idx is an index in the 128 bits
173 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
174 /// lowering INSERT_VECTOR_ELT operations easier.
175 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
176                                   SelectionDAG &DAG,SDLoc dl) {
177   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
178   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
179 }
180
181 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
182                                   SelectionDAG &DAG, SDLoc dl) {
183   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
184   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
185 }
186
187 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
188 /// instructions. This is used because creating CONCAT_VECTOR nodes of
189 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
190 /// large BUILD_VECTORS.
191 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
192                                    unsigned NumElems, SelectionDAG &DAG,
193                                    SDLoc dl) {
194   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
195   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
196 }
197
198 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
199                                    unsigned NumElems, SelectionDAG &DAG,
200                                    SDLoc dl) {
201   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
202   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
203 }
204
205 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
206                                      const X86Subtarget &STI)
207     : TargetLowering(TM), Subtarget(&STI) {
208   X86ScalarSSEf64 = Subtarget->hasSSE2();
209   X86ScalarSSEf32 = Subtarget->hasSSE1();
210   TD = getDataLayout();
211
212   // Set up the TargetLowering object.
213   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
214
215   // X86 is weird. It always uses i8 for shift amounts and setcc results.
216   setBooleanContents(ZeroOrOneBooleanContent);
217   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
218   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
219
220   // For 64-bit, since we have so many registers, use the ILP scheduler.
221   // For 32-bit, use the register pressure specific scheduling.
222   // For Atom, always use ILP scheduling.
223   if (Subtarget->isAtom())
224     setSchedulingPreference(Sched::ILP);
225   else if (Subtarget->is64Bit())
226     setSchedulingPreference(Sched::ILP);
227   else
228     setSchedulingPreference(Sched::RegPressure);
229   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
230   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
231
232   // Bypass expensive divides on Atom when compiling with O2.
233   if (TM.getOptLevel() >= CodeGenOpt::Default) {
234     if (Subtarget->hasSlowDivide32())
235       addBypassSlowDiv(32, 8);
236     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
237       addBypassSlowDiv(64, 16);
238   }
239
240   if (Subtarget->isTargetKnownWindowsMSVC()) {
241     // Setup Windows compiler runtime calls.
242     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
243     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
244     setLibcallName(RTLIB::SREM_I64, "_allrem");
245     setLibcallName(RTLIB::UREM_I64, "_aullrem");
246     setLibcallName(RTLIB::MUL_I64, "_allmul");
247     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
248     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
249     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
250     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
251     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
252
253     // The _ftol2 runtime function has an unusual calling conv, which
254     // is modeled by a special pseudo-instruction.
255     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
256     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
257     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
258     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
259   }
260
261   if (Subtarget->isTargetDarwin()) {
262     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
263     setUseUnderscoreSetJmp(false);
264     setUseUnderscoreLongJmp(false);
265   } else if (Subtarget->isTargetWindowsGNU()) {
266     // MS runtime is weird: it exports _setjmp, but longjmp!
267     setUseUnderscoreSetJmp(true);
268     setUseUnderscoreLongJmp(false);
269   } else {
270     setUseUnderscoreSetJmp(true);
271     setUseUnderscoreLongJmp(true);
272   }
273
274   // Set up the register classes.
275   addRegisterClass(MVT::i8, &X86::GR8RegClass);
276   addRegisterClass(MVT::i16, &X86::GR16RegClass);
277   addRegisterClass(MVT::i32, &X86::GR32RegClass);
278   if (Subtarget->is64Bit())
279     addRegisterClass(MVT::i64, &X86::GR64RegClass);
280
281   for (MVT VT : MVT::integer_valuetypes())
282     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
283
284   // We don't accept any truncstore of integer registers.
285   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
286   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
287   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
288   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
289   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
290   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
291
292   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
293
294   // SETOEQ and SETUNE require checking two conditions.
295   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
296   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
297   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
298   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
299   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
300   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
301
302   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
303   // operation.
304   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
305   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
306   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
307
308   if (Subtarget->is64Bit()) {
309     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
310     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
311   } else if (!TM.Options.UseSoftFloat) {
312     // We have an algorithm for SSE2->double, and we turn this into a
313     // 64-bit FILD followed by conditional FADD for other targets.
314     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
315     // We have an algorithm for SSE2, and we turn this into a 64-bit
316     // FILD for other targets.
317     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
318   }
319
320   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
321   // this operation.
322   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
323   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
324
325   if (!TM.Options.UseSoftFloat) {
326     // SSE has no i16 to fp conversion, only i32
327     if (X86ScalarSSEf32) {
328       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
329       // f32 and f64 cases are Legal, f80 case is not
330       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
331     } else {
332       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
333       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
334     }
335   } else {
336     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
337     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
338   }
339
340   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
341   // are Legal, f80 is custom lowered.
342   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
343   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
344
345   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
348   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
349
350   if (X86ScalarSSEf32) {
351     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
352     // f32 and f64 cases are Legal, f80 case is not
353     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
354   } else {
355     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
356     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
357   }
358
359   // Handle FP_TO_UINT by promoting the destination to a larger signed
360   // conversion.
361   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
362   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
363   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
364
365   if (Subtarget->is64Bit()) {
366     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
367     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
368   } else if (!TM.Options.UseSoftFloat) {
369     // Since AVX is a superset of SSE3, only check for SSE here.
370     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
371       // Expand FP_TO_UINT into a select.
372       // FIXME: We would like to use a Custom expander here eventually to do
373       // the optimal thing for SSE vs. the default expansion in the legalizer.
374       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
375     else
376       // With SSE3 we can use fisttpll to convert to a signed i64; without
377       // SSE, we're stuck with a fistpll.
378       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
379   }
380
381   if (isTargetFTOL()) {
382     // Use the _ftol2 runtime function, which has a pseudo-instruction
383     // to handle its weird calling convention.
384     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
385   }
386
387   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
388   if (!X86ScalarSSEf64) {
389     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
390     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
391     if (Subtarget->is64Bit()) {
392       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
393       // Without SSE, i64->f64 goes through memory.
394       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
395     }
396   }
397
398   // Scalar integer divide and remainder are lowered to use operations that
399   // produce two results, to match the available instructions. This exposes
400   // the two-result form to trivial CSE, which is able to combine x/y and x%y
401   // into a single instruction.
402   //
403   // Scalar integer multiply-high is also lowered to use two-result
404   // operations, to match the available instructions. However, plain multiply
405   // (low) operations are left as Legal, as there are single-result
406   // instructions for this in x86. Using the two-result multiply instructions
407   // when both high and low results are needed must be arranged by dagcombine.
408   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
409     MVT VT = IntVTs[i];
410     setOperationAction(ISD::MULHS, VT, Expand);
411     setOperationAction(ISD::MULHU, VT, Expand);
412     setOperationAction(ISD::SDIV, VT, Expand);
413     setOperationAction(ISD::UDIV, VT, Expand);
414     setOperationAction(ISD::SREM, VT, Expand);
415     setOperationAction(ISD::UREM, VT, Expand);
416
417     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
418     setOperationAction(ISD::ADDC, VT, Custom);
419     setOperationAction(ISD::ADDE, VT, Custom);
420     setOperationAction(ISD::SUBC, VT, Custom);
421     setOperationAction(ISD::SUBE, VT, Custom);
422   }
423
424   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
425   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
426   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
427   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
428   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
429   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
430   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
431   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
432   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
433   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
434   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
435   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
436   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
437   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
438   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
439   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
440   if (Subtarget->is64Bit())
441     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
442   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
443   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
444   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
445   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
446   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
447   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
448   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
449   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
450
451   // Promote the i8 variants and force them on up to i32 which has a shorter
452   // encoding.
453   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
454   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
455   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
456   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
457   if (Subtarget->hasBMI()) {
458     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
459     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
460     if (Subtarget->is64Bit())
461       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
462   } else {
463     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
464     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
465     if (Subtarget->is64Bit())
466       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
467   }
468
469   if (Subtarget->hasLZCNT()) {
470     // When promoting the i8 variants, force them to i32 for a shorter
471     // encoding.
472     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
473     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
474     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
475     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
476     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
477     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
478     if (Subtarget->is64Bit())
479       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
480   } else {
481     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
482     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
483     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
484     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
485     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
486     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
487     if (Subtarget->is64Bit()) {
488       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
489       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
490     }
491   }
492
493   // Special handling for half-precision floating point conversions.
494   // If we don't have F16C support, then lower half float conversions
495   // into library calls.
496   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
497     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
498     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
499   }
500
501   // There's never any support for operations beyond MVT::f32.
502   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
503   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
504   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
505   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
506
507   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
508   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
509   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
510   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
511   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
512   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
513
514   if (Subtarget->hasPOPCNT()) {
515     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
516   } else {
517     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
518     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
519     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
520     if (Subtarget->is64Bit())
521       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
522   }
523
524   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
525
526   if (!Subtarget->hasMOVBE())
527     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
528
529   // These should be promoted to a larger select which is supported.
530   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
531   // X86 wants to expand cmov itself.
532   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
533   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
534   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
535   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
536   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
537   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
538   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
539   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
540   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
541   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
542   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
543   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
544   if (Subtarget->is64Bit()) {
545     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
546     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
547   }
548   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
549   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
550   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
551   // support continuation, user-level threading, and etc.. As a result, no
552   // other SjLj exception interfaces are implemented and please don't build
553   // your own exception handling based on them.
554   // LLVM/Clang supports zero-cost DWARF exception handling.
555   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
556   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
557
558   // Darwin ABI issue.
559   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
560   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
561   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
562   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
563   if (Subtarget->is64Bit())
564     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
565   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
566   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
569     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
570     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
571     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
572     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
573   }
574   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
575   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
576   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
577   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
578   if (Subtarget->is64Bit()) {
579     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
580     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
581     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
582   }
583
584   if (Subtarget->hasSSE1())
585     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
586
587   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
588
589   // Expand certain atomics
590   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
591     MVT VT = IntVTs[i];
592     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
594     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
595   }
596
597   if (Subtarget->hasCmpxchg16b()) {
598     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
599   }
600
601   // FIXME - use subtarget debug flags
602   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
603       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
604     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
605   }
606
607   if (Subtarget->is64Bit()) {
608     setExceptionPointerRegister(X86::RAX);
609     setExceptionSelectorRegister(X86::RDX);
610   } else {
611     setExceptionPointerRegister(X86::EAX);
612     setExceptionSelectorRegister(X86::EDX);
613   }
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616
617   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619
620   setOperationAction(ISD::TRAP, MVT::Other, Legal);
621   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622
623   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
625   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
626   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627     // TargetInfo::X86_64ABIBuiltinVaList
628     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
629     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
630   } else {
631     // TargetInfo::CharPtrBuiltinVaList
632     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
633     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
634   }
635
636   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
637   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
638
639   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
640
641   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
642     // f32 and f64 use SSE.
643     // Set up the FP register classes.
644     addRegisterClass(MVT::f32, &X86::FR32RegClass);
645     addRegisterClass(MVT::f64, &X86::FR64RegClass);
646
647     // Use ANDPD to simulate FABS.
648     setOperationAction(ISD::FABS , MVT::f64, Custom);
649     setOperationAction(ISD::FABS , MVT::f32, Custom);
650
651     // Use XORP to simulate FNEG.
652     setOperationAction(ISD::FNEG , MVT::f64, Custom);
653     setOperationAction(ISD::FNEG , MVT::f32, Custom);
654
655     // Use ANDPD and ORPD to simulate FCOPYSIGN.
656     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
657     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
658
659     // Lower this to FGETSIGNx86 plus an AND.
660     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
661     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
662
663     // We don't support sin/cos/fmod
664     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
665     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
666     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
667     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
670
671     // Expand FP immediates into loads from the stack, except for the special
672     // cases we handle.
673     addLegalFPImmediate(APFloat(+0.0)); // xorpd
674     addLegalFPImmediate(APFloat(+0.0f)); // xorps
675   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
676     // Use SSE for f32, x87 for f64.
677     // Set up the FP register classes.
678     addRegisterClass(MVT::f32, &X86::FR32RegClass);
679     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
680
681     // Use ANDPS to simulate FABS.
682     setOperationAction(ISD::FABS , MVT::f32, Custom);
683
684     // Use XORP to simulate FNEG.
685     setOperationAction(ISD::FNEG , MVT::f32, Custom);
686
687     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
688
689     // Use ANDPS and ORPS to simulate FCOPYSIGN.
690     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
691     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
692
693     // We don't support sin/cos/fmod
694     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
695     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
696     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
697
698     // Special cases we handle for FP constants.
699     addLegalFPImmediate(APFloat(+0.0f)); // xorps
700     addLegalFPImmediate(APFloat(+0.0)); // FLD0
701     addLegalFPImmediate(APFloat(+1.0)); // FLD1
702     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
703     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
704
705     if (!TM.Options.UnsafeFPMath) {
706       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
707       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
708       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
709     }
710   } else if (!TM.Options.UseSoftFloat) {
711     // f32 and f64 in x87.
712     // Set up the FP register classes.
713     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
714     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
715
716     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
717     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
718     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
720
721     if (!TM.Options.UnsafeFPMath) {
722       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
723       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
724       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
725       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
726       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
727       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
728     }
729     addLegalFPImmediate(APFloat(+0.0)); // FLD0
730     addLegalFPImmediate(APFloat(+1.0)); // FLD1
731     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
732     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
733     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
734     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
735     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
736     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
737   }
738
739   // We don't support FMA.
740   setOperationAction(ISD::FMA, MVT::f64, Expand);
741   setOperationAction(ISD::FMA, MVT::f32, Expand);
742
743   // Long double always uses X87.
744   if (!TM.Options.UseSoftFloat) {
745     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
746     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
747     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
748     {
749       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
750       addLegalFPImmediate(TmpFlt);  // FLD0
751       TmpFlt.changeSign();
752       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
753
754       bool ignored;
755       APFloat TmpFlt2(+1.0);
756       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
757                       &ignored);
758       addLegalFPImmediate(TmpFlt2);  // FLD1
759       TmpFlt2.changeSign();
760       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
761     }
762
763     if (!TM.Options.UnsafeFPMath) {
764       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
765       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
766       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
767     }
768
769     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
770     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
771     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
772     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
773     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
774     setOperationAction(ISD::FMA, MVT::f80, Expand);
775   }
776
777   // Always use a library call for pow.
778   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
779   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
781
782   setOperationAction(ISD::FLOG, MVT::f80, Expand);
783   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
785   setOperationAction(ISD::FEXP, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
787   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
788   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
789
790   // First set operation action for all vector types to either promote
791   // (for widening) or expand (for scalarization). Then we will selectively
792   // turn on ones that can be effectively codegen'd.
793   for (MVT VT : MVT::vector_valuetypes()) {
794     setOperationAction(ISD::ADD , VT, Expand);
795     setOperationAction(ISD::SUB , VT, Expand);
796     setOperationAction(ISD::FADD, VT, Expand);
797     setOperationAction(ISD::FNEG, VT, Expand);
798     setOperationAction(ISD::FSUB, VT, Expand);
799     setOperationAction(ISD::MUL , VT, Expand);
800     setOperationAction(ISD::FMUL, VT, Expand);
801     setOperationAction(ISD::SDIV, VT, Expand);
802     setOperationAction(ISD::UDIV, VT, Expand);
803     setOperationAction(ISD::FDIV, VT, Expand);
804     setOperationAction(ISD::SREM, VT, Expand);
805     setOperationAction(ISD::UREM, VT, Expand);
806     setOperationAction(ISD::LOAD, VT, Expand);
807     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
808     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
809     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
810     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
811     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
812     setOperationAction(ISD::FABS, VT, Expand);
813     setOperationAction(ISD::FSIN, VT, Expand);
814     setOperationAction(ISD::FSINCOS, VT, Expand);
815     setOperationAction(ISD::FCOS, VT, Expand);
816     setOperationAction(ISD::FSINCOS, VT, Expand);
817     setOperationAction(ISD::FREM, VT, Expand);
818     setOperationAction(ISD::FMA,  VT, Expand);
819     setOperationAction(ISD::FPOWI, VT, Expand);
820     setOperationAction(ISD::FSQRT, VT, Expand);
821     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
822     setOperationAction(ISD::FFLOOR, VT, Expand);
823     setOperationAction(ISD::FCEIL, VT, Expand);
824     setOperationAction(ISD::FTRUNC, VT, Expand);
825     setOperationAction(ISD::FRINT, VT, Expand);
826     setOperationAction(ISD::FNEARBYINT, VT, Expand);
827     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
828     setOperationAction(ISD::MULHS, VT, Expand);
829     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
830     setOperationAction(ISD::MULHU, VT, Expand);
831     setOperationAction(ISD::SDIVREM, VT, Expand);
832     setOperationAction(ISD::UDIVREM, VT, Expand);
833     setOperationAction(ISD::FPOW, VT, Expand);
834     setOperationAction(ISD::CTPOP, VT, Expand);
835     setOperationAction(ISD::CTTZ, VT, Expand);
836     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
837     setOperationAction(ISD::CTLZ, VT, Expand);
838     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
839     setOperationAction(ISD::SHL, VT, Expand);
840     setOperationAction(ISD::SRA, VT, Expand);
841     setOperationAction(ISD::SRL, VT, Expand);
842     setOperationAction(ISD::ROTL, VT, Expand);
843     setOperationAction(ISD::ROTR, VT, Expand);
844     setOperationAction(ISD::BSWAP, VT, Expand);
845     setOperationAction(ISD::SETCC, VT, Expand);
846     setOperationAction(ISD::FLOG, VT, Expand);
847     setOperationAction(ISD::FLOG2, VT, Expand);
848     setOperationAction(ISD::FLOG10, VT, Expand);
849     setOperationAction(ISD::FEXP, VT, Expand);
850     setOperationAction(ISD::FEXP2, VT, Expand);
851     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
852     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
853     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
854     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
856     setOperationAction(ISD::TRUNCATE, VT, Expand);
857     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
858     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
859     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
860     setOperationAction(ISD::VSELECT, VT, Expand);
861     setOperationAction(ISD::SELECT_CC, VT, Expand);
862     for (MVT InnerVT : MVT::vector_valuetypes()) {
863       setTruncStoreAction(InnerVT, VT, Expand);
864
865       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
866       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
867
868       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
869       // types, we have to deal with them whether we ask for Expansion or not.
870       // Setting Expand causes its own optimisation problems though, so leave
871       // them legal.
872       if (VT.getVectorElementType() == MVT::i1)
873         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
874     }
875   }
876
877   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
878   // with -msoft-float, disable use of MMX as well.
879   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
880     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
881     // No operations on x86mmx supported, everything uses intrinsics.
882   }
883
884   // MMX-sized vectors (other than x86mmx) are expected to be expanded
885   // into smaller operations.
886   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
887   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
888   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
889   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
890   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
891   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
892   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
893   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
894   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
895   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
896   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
897   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
898   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
899   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
900   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
901   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
902   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
903   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
904   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
905   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
906   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
907   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
908   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
909   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
910   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
911   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
912   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
913   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
914   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
915
916   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
917     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
918
919     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
920     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
921     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
922     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
923     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
924     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
925     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
926     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
927     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
928     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
929     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
930     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
931     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
932   }
933
934   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
935     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
936
937     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
938     // registers cannot be used even for integer operations.
939     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
940     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
941     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
942     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
943
944     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
945     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
946     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
947     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
948     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
949     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
950     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
951     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
952     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
953     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
954     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
955     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
956     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
957     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
958     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
959     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
960     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
961     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
962     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
963     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
964     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
965     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
966
967     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
968     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
969     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
970     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
971
972     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
973     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
974     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
975     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
976     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
977
978     // Only provide customized ctpop vector bit twiddling for vector types we
979     // know to perform better than using the popcnt instructions on each vector
980     // element. If popcnt isn't supported, always provide the custom version.
981     if (!Subtarget->hasPOPCNT()) {
982       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
983       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
984     }
985
986     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
987     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
988       MVT VT = (MVT::SimpleValueType)i;
989       // Do not attempt to custom lower non-power-of-2 vectors
990       if (!isPowerOf2_32(VT.getVectorNumElements()))
991         continue;
992       // Do not attempt to custom lower non-128-bit vectors
993       if (!VT.is128BitVector())
994         continue;
995       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
996       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
997       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
998     }
999
1000     // We support custom legalizing of sext and anyext loads for specific
1001     // memory vector types which we can load as a scalar (or sequence of
1002     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1003     // loads these must work with a single scalar load.
1004     for (MVT VT : MVT::integer_vector_valuetypes()) {
1005       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
1006       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
1007       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
1008       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
1009       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
1010       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
1011       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
1012       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
1013       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
1014     }
1015
1016     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1017     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1018     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1019     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1020     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1021     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1022
1023     if (Subtarget->is64Bit()) {
1024       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1025       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1026     }
1027
1028     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1029     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1030       MVT VT = (MVT::SimpleValueType)i;
1031
1032       // Do not attempt to promote non-128-bit vectors
1033       if (!VT.is128BitVector())
1034         continue;
1035
1036       setOperationAction(ISD::AND,    VT, Promote);
1037       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1038       setOperationAction(ISD::OR,     VT, Promote);
1039       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1040       setOperationAction(ISD::XOR,    VT, Promote);
1041       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1042       setOperationAction(ISD::LOAD,   VT, Promote);
1043       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1044       setOperationAction(ISD::SELECT, VT, Promote);
1045       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1046     }
1047
1048     // Custom lower v2i64 and v2f64 selects.
1049     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1050     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1051     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1052     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1053
1054     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1055     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1056
1057     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1058     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1059     // As there is no 64-bit GPR available, we need build a special custom
1060     // sequence to convert from v2i32 to v2f32.
1061     if (!Subtarget->is64Bit())
1062       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1063
1064     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1065     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1066
1067     for (MVT VT : MVT::fp_vector_valuetypes())
1068       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1069
1070     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1071     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1072     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1073   }
1074
1075   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1076     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1077     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1078     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1079     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1080     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1081     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1082     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1083     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1084     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1085     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1086
1087     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1088     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1089     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1090     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1091     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1092     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1093     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1094     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1095     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1096     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1097
1098     // FIXME: Do we need to handle scalar-to-vector here?
1099     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1100
1101     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1102     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1103     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1104     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1105     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1106     // There is no BLENDI for byte vectors. We don't need to custom lower
1107     // some vselects for now.
1108     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1109
1110     // SSE41 brings specific instructions for doing vector sign extend even in
1111     // cases where we don't have SRA.
1112     for (MVT VT : MVT::integer_vector_valuetypes()) {
1113       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1114       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1115       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1116     }
1117
1118     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1119     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1120     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1121     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1122     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1123     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1124     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1125
1126     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1127     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1128     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1129     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1130     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1131     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1132
1133     // i8 and i16 vectors are custom because the source register and source
1134     // source memory operand types are not the same width.  f32 vectors are
1135     // custom since the immediate controlling the insert encodes additional
1136     // information.
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1138     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1139     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1140     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1141
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1143     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1144     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1145     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1146
1147     // FIXME: these should be Legal, but that's only for the case where
1148     // the index is constant.  For now custom expand to deal with that.
1149     if (Subtarget->is64Bit()) {
1150       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1151       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1152     }
1153   }
1154
1155   if (Subtarget->hasSSE2()) {
1156     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1157     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1158
1159     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1160     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1161
1162     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1163     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1164
1165     // In the customized shift lowering, the legal cases in AVX2 will be
1166     // recognized.
1167     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1168     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1169
1170     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1171     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1172
1173     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1174   }
1175
1176   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1177     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1179     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1180     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1181     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1182     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1183
1184     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1185     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1186     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1187
1188     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1190     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1191     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1192     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1194     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1195     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1196     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1197     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1198     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1199     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1200
1201     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1203     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1204     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1205     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1207     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1208     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1209     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1210     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1211     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1212     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1213
1214     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1215     // even though v8i16 is a legal type.
1216     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1217     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1218     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1219
1220     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1221     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1222     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1223
1224     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1225     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1226
1227     for (MVT VT : MVT::fp_vector_valuetypes())
1228       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1229
1230     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1231     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1232
1233     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1234     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1235
1236     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1237     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1238
1239     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1240     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1241     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1242     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1243
1244     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1245     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1246     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1247
1248     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1249     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1250     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1251     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1252
1253     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1254     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1255     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1256     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1257     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1258     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1259     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1260     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1261     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1262     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1263     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1264     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1265
1266     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1267       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1268       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1269       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1270       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1271       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1272       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1273     }
1274
1275     if (Subtarget->hasInt256()) {
1276       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1277       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1278       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1279       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1280
1281       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1282       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1283       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1284       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1285
1286       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1287       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1288       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1289       // Don't lower v32i8 because there is no 128-bit byte mul
1290
1291       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1292       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1293       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1294       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1295
1296       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1297       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1298
1299       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1300       // when we have a 256bit-wide blend with immediate.
1301       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1302
1303       // Only provide customized ctpop vector bit twiddling for vector types we
1304       // know to perform better than using the popcnt instructions on each
1305       // vector element. If popcnt isn't supported, always provide the custom
1306       // version.
1307       if (!Subtarget->hasPOPCNT())
1308         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1309
1310       // Custom CTPOP always performs better on natively supported v8i32
1311       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1312
1313       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1314       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1315       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1316       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1317       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1318       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1319       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1320
1321       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1322       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1323       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1324       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1325       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1326       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1327     } else {
1328       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1329       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1330       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1331       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1332
1333       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1334       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1335       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1336       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1337
1338       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1339       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1340       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1341       // Don't lower v32i8 because there is no 128-bit byte mul
1342     }
1343
1344     // In the customized shift lowering, the legal cases in AVX2 will be
1345     // recognized.
1346     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1347     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1348
1349     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1350     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1351
1352     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1353
1354     // Custom lower several nodes for 256-bit types.
1355     for (MVT VT : MVT::vector_valuetypes()) {
1356       if (VT.getScalarSizeInBits() >= 32) {
1357         setOperationAction(ISD::MLOAD,  VT, Legal);
1358         setOperationAction(ISD::MSTORE, VT, Legal);
1359       }
1360       // Extract subvector is special because the value type
1361       // (result) is 128-bit but the source is 256-bit wide.
1362       if (VT.is128BitVector()) {
1363         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1364       }
1365       // Do not attempt to custom lower other non-256-bit vectors
1366       if (!VT.is256BitVector())
1367         continue;
1368
1369       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1370       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1371       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1372       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1373       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1374       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1375       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1376     }
1377
1378     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1379     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1380       MVT VT = (MVT::SimpleValueType)i;
1381
1382       // Do not attempt to promote non-256-bit vectors
1383       if (!VT.is256BitVector())
1384         continue;
1385
1386       setOperationAction(ISD::AND,    VT, Promote);
1387       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1388       setOperationAction(ISD::OR,     VT, Promote);
1389       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1390       setOperationAction(ISD::XOR,    VT, Promote);
1391       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1392       setOperationAction(ISD::LOAD,   VT, Promote);
1393       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1394       setOperationAction(ISD::SELECT, VT, Promote);
1395       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1396     }
1397   }
1398
1399   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1400     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1401     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1402     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1403     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1404
1405     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1406     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1407     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1408
1409     for (MVT VT : MVT::fp_vector_valuetypes())
1410       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1411
1412     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1413     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1414     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1415     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1416     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1417     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1418     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1419     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1420     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1421     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1422
1423     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1424     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1425     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1426     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1427     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1428     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1429
1430     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1431     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1432     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1433     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1434     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1435     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1436     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1437     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1438
1439     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1440     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1441     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1442     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1443     if (Subtarget->is64Bit()) {
1444       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1445       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1446       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1447       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1448     }
1449     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1450     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1451     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1452     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1453     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1454     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1455     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1456     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1457     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1458     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1459     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1460     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1461     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1462     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1463
1464     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1465     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1466     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1467     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1468     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1469     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1470     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1471     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1472     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1473     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1474     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1475     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1476     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1477
1478     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1479     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1480     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1481     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1482     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1483     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1484
1485     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1486     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1487
1488     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1489
1490     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1491     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1492     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1493     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1494     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1495     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1496     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1497     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1498     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1499
1500     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1501     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1502
1503     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1504     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1505
1506     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1507
1508     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1509     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1510
1511     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1512     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1513
1514     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1515     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1516
1517     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1518     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1519     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1520     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1521     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1522     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1523
1524     if (Subtarget->hasCDI()) {
1525       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1526       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1527     }
1528
1529     // Custom lower several nodes.
1530     for (MVT VT : MVT::vector_valuetypes()) {
1531       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1532       // Extract subvector is special because the value type
1533       // (result) is 256/128-bit but the source is 512-bit wide.
1534       if (VT.is128BitVector() || VT.is256BitVector()) {
1535         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1536       }
1537       if (VT.getVectorElementType() == MVT::i1)
1538         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1539
1540       // Do not attempt to custom lower other non-512-bit vectors
1541       if (!VT.is512BitVector())
1542         continue;
1543
1544       if ( EltSize >= 32) {
1545         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1546         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1547         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1548         setOperationAction(ISD::VSELECT,             VT, Legal);
1549         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1550         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1551         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1552         setOperationAction(ISD::MLOAD,               VT, Legal);
1553         setOperationAction(ISD::MSTORE,              VT, Legal);
1554       }
1555     }
1556     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1557       MVT VT = (MVT::SimpleValueType)i;
1558
1559       // Do not attempt to promote non-512-bit vectors.
1560       if (!VT.is512BitVector())
1561         continue;
1562
1563       setOperationAction(ISD::SELECT, VT, Promote);
1564       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1565     }
1566   }// has  AVX-512
1567
1568   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1569     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1570     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1571
1572     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1573     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1574
1575     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1576     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1577     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1578     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1579     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1580     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1581     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1582     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1583     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1584
1585     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1586       const MVT VT = (MVT::SimpleValueType)i;
1587
1588       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1589
1590       // Do not attempt to promote non-512-bit vectors.
1591       if (!VT.is512BitVector())
1592         continue;
1593
1594       if (EltSize < 32) {
1595         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1596         setOperationAction(ISD::VSELECT,             VT, Legal);
1597       }
1598     }
1599   }
1600
1601   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1602     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1603     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1604
1605     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1606     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1607     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1608
1609     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1610     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1611     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1612     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1613     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1614     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1615   }
1616
1617   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1618   // of this type with custom code.
1619   for (MVT VT : MVT::vector_valuetypes())
1620     setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1621
1622   // We want to custom lower some of our intrinsics.
1623   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1624   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1625   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1626   if (!Subtarget->is64Bit())
1627     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1628
1629   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1630   // handle type legalization for these operations here.
1631   //
1632   // FIXME: We really should do custom legalization for addition and
1633   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1634   // than generic legalization for 64-bit multiplication-with-overflow, though.
1635   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1636     // Add/Sub/Mul with overflow operations are custom lowered.
1637     MVT VT = IntVTs[i];
1638     setOperationAction(ISD::SADDO, VT, Custom);
1639     setOperationAction(ISD::UADDO, VT, Custom);
1640     setOperationAction(ISD::SSUBO, VT, Custom);
1641     setOperationAction(ISD::USUBO, VT, Custom);
1642     setOperationAction(ISD::SMULO, VT, Custom);
1643     setOperationAction(ISD::UMULO, VT, Custom);
1644   }
1645
1646
1647   if (!Subtarget->is64Bit()) {
1648     // These libcalls are not available in 32-bit.
1649     setLibcallName(RTLIB::SHL_I128, nullptr);
1650     setLibcallName(RTLIB::SRL_I128, nullptr);
1651     setLibcallName(RTLIB::SRA_I128, nullptr);
1652   }
1653
1654   // Combine sin / cos into one node or libcall if possible.
1655   if (Subtarget->hasSinCos()) {
1656     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1657     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1658     if (Subtarget->isTargetDarwin()) {
1659       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1660       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1661       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1662       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1663     }
1664   }
1665
1666   if (Subtarget->isTargetWin64()) {
1667     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1668     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1669     setOperationAction(ISD::SREM, MVT::i128, Custom);
1670     setOperationAction(ISD::UREM, MVT::i128, Custom);
1671     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1672     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1673   }
1674
1675   // We have target-specific dag combine patterns for the following nodes:
1676   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1677   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1678   setTargetDAGCombine(ISD::BITCAST);
1679   setTargetDAGCombine(ISD::VSELECT);
1680   setTargetDAGCombine(ISD::SELECT);
1681   setTargetDAGCombine(ISD::SHL);
1682   setTargetDAGCombine(ISD::SRA);
1683   setTargetDAGCombine(ISD::SRL);
1684   setTargetDAGCombine(ISD::OR);
1685   setTargetDAGCombine(ISD::AND);
1686   setTargetDAGCombine(ISD::ADD);
1687   setTargetDAGCombine(ISD::FADD);
1688   setTargetDAGCombine(ISD::FSUB);
1689   setTargetDAGCombine(ISD::FMA);
1690   setTargetDAGCombine(ISD::SUB);
1691   setTargetDAGCombine(ISD::LOAD);
1692   setTargetDAGCombine(ISD::MLOAD);
1693   setTargetDAGCombine(ISD::STORE);
1694   setTargetDAGCombine(ISD::MSTORE);
1695   setTargetDAGCombine(ISD::ZERO_EXTEND);
1696   setTargetDAGCombine(ISD::ANY_EXTEND);
1697   setTargetDAGCombine(ISD::SIGN_EXTEND);
1698   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1699   setTargetDAGCombine(ISD::TRUNCATE);
1700   setTargetDAGCombine(ISD::SINT_TO_FP);
1701   setTargetDAGCombine(ISD::SETCC);
1702   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1703   setTargetDAGCombine(ISD::BUILD_VECTOR);
1704   setTargetDAGCombine(ISD::MUL);
1705   setTargetDAGCombine(ISD::XOR);
1706
1707   computeRegisterProperties();
1708
1709   // On Darwin, -Os means optimize for size without hurting performance,
1710   // do not reduce the limit.
1711   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1712   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1713   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1714   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1715   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1716   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1717   setPrefLoopAlignment(4); // 2^4 bytes.
1718
1719   // Predictable cmov don't hurt on atom because it's in-order.
1720   PredictableSelectIsExpensive = !Subtarget->isAtom();
1721   EnableExtLdPromotion = true;
1722   setPrefFunctionAlignment(4); // 2^4 bytes.
1723
1724   verifyIntrinsicTables();
1725 }
1726
1727 // This has so far only been implemented for 64-bit MachO.
1728 bool X86TargetLowering::useLoadStackGuardNode() const {
1729   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1730 }
1731
1732 TargetLoweringBase::LegalizeTypeAction
1733 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1734   if (ExperimentalVectorWideningLegalization &&
1735       VT.getVectorNumElements() != 1 &&
1736       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1737     return TypeWidenVector;
1738
1739   return TargetLoweringBase::getPreferredVectorAction(VT);
1740 }
1741
1742 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1743   if (!VT.isVector())
1744     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1745
1746   const unsigned NumElts = VT.getVectorNumElements();
1747   const EVT EltVT = VT.getVectorElementType();
1748   if (VT.is512BitVector()) {
1749     if (Subtarget->hasAVX512())
1750       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1751           EltVT == MVT::f32 || EltVT == MVT::f64)
1752         switch(NumElts) {
1753         case  8: return MVT::v8i1;
1754         case 16: return MVT::v16i1;
1755       }
1756     if (Subtarget->hasBWI())
1757       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1758         switch(NumElts) {
1759         case 32: return MVT::v32i1;
1760         case 64: return MVT::v64i1;
1761       }
1762   }
1763
1764   if (VT.is256BitVector() || VT.is128BitVector()) {
1765     if (Subtarget->hasVLX())
1766       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1767           EltVT == MVT::f32 || EltVT == MVT::f64)
1768         switch(NumElts) {
1769         case 2: return MVT::v2i1;
1770         case 4: return MVT::v4i1;
1771         case 8: return MVT::v8i1;
1772       }
1773     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1774       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1775         switch(NumElts) {
1776         case  8: return MVT::v8i1;
1777         case 16: return MVT::v16i1;
1778         case 32: return MVT::v32i1;
1779       }
1780   }
1781
1782   return VT.changeVectorElementTypeToInteger();
1783 }
1784
1785 /// Helper for getByValTypeAlignment to determine
1786 /// the desired ByVal argument alignment.
1787 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1788   if (MaxAlign == 16)
1789     return;
1790   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1791     if (VTy->getBitWidth() == 128)
1792       MaxAlign = 16;
1793   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1794     unsigned EltAlign = 0;
1795     getMaxByValAlign(ATy->getElementType(), EltAlign);
1796     if (EltAlign > MaxAlign)
1797       MaxAlign = EltAlign;
1798   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1799     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1800       unsigned EltAlign = 0;
1801       getMaxByValAlign(STy->getElementType(i), EltAlign);
1802       if (EltAlign > MaxAlign)
1803         MaxAlign = EltAlign;
1804       if (MaxAlign == 16)
1805         break;
1806     }
1807   }
1808 }
1809
1810 /// Return the desired alignment for ByVal aggregate
1811 /// function arguments in the caller parameter area. For X86, aggregates
1812 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1813 /// are at 4-byte boundaries.
1814 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1815   if (Subtarget->is64Bit()) {
1816     // Max of 8 and alignment of type.
1817     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1818     if (TyAlign > 8)
1819       return TyAlign;
1820     return 8;
1821   }
1822
1823   unsigned Align = 4;
1824   if (Subtarget->hasSSE1())
1825     getMaxByValAlign(Ty, Align);
1826   return Align;
1827 }
1828
1829 /// Returns the target specific optimal type for load
1830 /// and store operations as a result of memset, memcpy, and memmove
1831 /// lowering. If DstAlign is zero that means it's safe to destination
1832 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1833 /// means there isn't a need to check it against alignment requirement,
1834 /// probably because the source does not need to be loaded. If 'IsMemset' is
1835 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1836 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1837 /// source is constant so it does not need to be loaded.
1838 /// It returns EVT::Other if the type should be determined using generic
1839 /// target-independent logic.
1840 EVT
1841 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1842                                        unsigned DstAlign, unsigned SrcAlign,
1843                                        bool IsMemset, bool ZeroMemset,
1844                                        bool MemcpyStrSrc,
1845                                        MachineFunction &MF) const {
1846   const Function *F = MF.getFunction();
1847   if ((!IsMemset || ZeroMemset) &&
1848       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1849     if (Size >= 16 &&
1850         (Subtarget->isUnalignedMemAccessFast() ||
1851          ((DstAlign == 0 || DstAlign >= 16) &&
1852           (SrcAlign == 0 || SrcAlign >= 16)))) {
1853       if (Size >= 32) {
1854         if (Subtarget->hasInt256())
1855           return MVT::v8i32;
1856         if (Subtarget->hasFp256())
1857           return MVT::v8f32;
1858       }
1859       if (Subtarget->hasSSE2())
1860         return MVT::v4i32;
1861       if (Subtarget->hasSSE1())
1862         return MVT::v4f32;
1863     } else if (!MemcpyStrSrc && Size >= 8 &&
1864                !Subtarget->is64Bit() &&
1865                Subtarget->hasSSE2()) {
1866       // Do not use f64 to lower memcpy if source is string constant. It's
1867       // better to use i32 to avoid the loads.
1868       return MVT::f64;
1869     }
1870   }
1871   if (Subtarget->is64Bit() && Size >= 8)
1872     return MVT::i64;
1873   return MVT::i32;
1874 }
1875
1876 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1877   if (VT == MVT::f32)
1878     return X86ScalarSSEf32;
1879   else if (VT == MVT::f64)
1880     return X86ScalarSSEf64;
1881   return true;
1882 }
1883
1884 bool
1885 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1886                                                   unsigned,
1887                                                   unsigned,
1888                                                   bool *Fast) const {
1889   if (Fast)
1890     *Fast = Subtarget->isUnalignedMemAccessFast();
1891   return true;
1892 }
1893
1894 /// Return the entry encoding for a jump table in the
1895 /// current function.  The returned value is a member of the
1896 /// MachineJumpTableInfo::JTEntryKind enum.
1897 unsigned X86TargetLowering::getJumpTableEncoding() const {
1898   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1899   // symbol.
1900   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1901       Subtarget->isPICStyleGOT())
1902     return MachineJumpTableInfo::EK_Custom32;
1903
1904   // Otherwise, use the normal jump table encoding heuristics.
1905   return TargetLowering::getJumpTableEncoding();
1906 }
1907
1908 const MCExpr *
1909 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1910                                              const MachineBasicBlock *MBB,
1911                                              unsigned uid,MCContext &Ctx) const{
1912   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1913          Subtarget->isPICStyleGOT());
1914   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1915   // entries.
1916   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1917                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1918 }
1919
1920 /// Returns relocation base for the given PIC jumptable.
1921 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1922                                                     SelectionDAG &DAG) const {
1923   if (!Subtarget->is64Bit())
1924     // This doesn't have SDLoc associated with it, but is not really the
1925     // same as a Register.
1926     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1927   return Table;
1928 }
1929
1930 /// This returns the relocation base for the given PIC jumptable,
1931 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1932 const MCExpr *X86TargetLowering::
1933 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1934                              MCContext &Ctx) const {
1935   // X86-64 uses RIP relative addressing based on the jump table label.
1936   if (Subtarget->isPICStyleRIPRel())
1937     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1938
1939   // Otherwise, the reference is relative to the PIC base.
1940   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1941 }
1942
1943 // FIXME: Why this routine is here? Move to RegInfo!
1944 std::pair<const TargetRegisterClass*, uint8_t>
1945 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1946   const TargetRegisterClass *RRC = nullptr;
1947   uint8_t Cost = 1;
1948   switch (VT.SimpleTy) {
1949   default:
1950     return TargetLowering::findRepresentativeClass(VT);
1951   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1952     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1953     break;
1954   case MVT::x86mmx:
1955     RRC = &X86::VR64RegClass;
1956     break;
1957   case MVT::f32: case MVT::f64:
1958   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1959   case MVT::v4f32: case MVT::v2f64:
1960   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1961   case MVT::v4f64:
1962     RRC = &X86::VR128RegClass;
1963     break;
1964   }
1965   return std::make_pair(RRC, Cost);
1966 }
1967
1968 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1969                                                unsigned &Offset) const {
1970   if (!Subtarget->isTargetLinux())
1971     return false;
1972
1973   if (Subtarget->is64Bit()) {
1974     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1975     Offset = 0x28;
1976     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1977       AddressSpace = 256;
1978     else
1979       AddressSpace = 257;
1980   } else {
1981     // %gs:0x14 on i386
1982     Offset = 0x14;
1983     AddressSpace = 256;
1984   }
1985   return true;
1986 }
1987
1988 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1989                                             unsigned DestAS) const {
1990   assert(SrcAS != DestAS && "Expected different address spaces!");
1991
1992   return SrcAS < 256 && DestAS < 256;
1993 }
1994
1995 //===----------------------------------------------------------------------===//
1996 //               Return Value Calling Convention Implementation
1997 //===----------------------------------------------------------------------===//
1998
1999 #include "X86GenCallingConv.inc"
2000
2001 bool
2002 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2003                                   MachineFunction &MF, bool isVarArg,
2004                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2005                         LLVMContext &Context) const {
2006   SmallVector<CCValAssign, 16> RVLocs;
2007   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2008   return CCInfo.CheckReturn(Outs, RetCC_X86);
2009 }
2010
2011 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2012   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2013   return ScratchRegs;
2014 }
2015
2016 SDValue
2017 X86TargetLowering::LowerReturn(SDValue Chain,
2018                                CallingConv::ID CallConv, bool isVarArg,
2019                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2020                                const SmallVectorImpl<SDValue> &OutVals,
2021                                SDLoc dl, SelectionDAG &DAG) const {
2022   MachineFunction &MF = DAG.getMachineFunction();
2023   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2024
2025   SmallVector<CCValAssign, 16> RVLocs;
2026   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2027   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2028
2029   SDValue Flag;
2030   SmallVector<SDValue, 6> RetOps;
2031   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2032   // Operand #1 = Bytes To Pop
2033   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2034                    MVT::i16));
2035
2036   // Copy the result values into the output registers.
2037   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2038     CCValAssign &VA = RVLocs[i];
2039     assert(VA.isRegLoc() && "Can only return in registers!");
2040     SDValue ValToCopy = OutVals[i];
2041     EVT ValVT = ValToCopy.getValueType();
2042
2043     // Promote values to the appropriate types.
2044     if (VA.getLocInfo() == CCValAssign::SExt)
2045       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2046     else if (VA.getLocInfo() == CCValAssign::ZExt)
2047       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2048     else if (VA.getLocInfo() == CCValAssign::AExt)
2049       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2050     else if (VA.getLocInfo() == CCValAssign::BCvt)
2051       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2052
2053     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2054            "Unexpected FP-extend for return value.");
2055
2056     // If this is x86-64, and we disabled SSE, we can't return FP values,
2057     // or SSE or MMX vectors.
2058     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2059          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2060           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2061       report_fatal_error("SSE register return with SSE disabled");
2062     }
2063     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2064     // llvm-gcc has never done it right and no one has noticed, so this
2065     // should be OK for now.
2066     if (ValVT == MVT::f64 &&
2067         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2068       report_fatal_error("SSE2 register return with SSE2 disabled");
2069
2070     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2071     // the RET instruction and handled by the FP Stackifier.
2072     if (VA.getLocReg() == X86::FP0 ||
2073         VA.getLocReg() == X86::FP1) {
2074       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2075       // change the value to the FP stack register class.
2076       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2077         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2078       RetOps.push_back(ValToCopy);
2079       // Don't emit a copytoreg.
2080       continue;
2081     }
2082
2083     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2084     // which is returned in RAX / RDX.
2085     if (Subtarget->is64Bit()) {
2086       if (ValVT == MVT::x86mmx) {
2087         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2088           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2089           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2090                                   ValToCopy);
2091           // If we don't have SSE2 available, convert to v4f32 so the generated
2092           // register is legal.
2093           if (!Subtarget->hasSSE2())
2094             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2095         }
2096       }
2097     }
2098
2099     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2100     Flag = Chain.getValue(1);
2101     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2102   }
2103
2104   // The x86-64 ABIs require that for returning structs by value we copy
2105   // the sret argument into %rax/%eax (depending on ABI) for the return.
2106   // Win32 requires us to put the sret argument to %eax as well.
2107   // We saved the argument into a virtual register in the entry block,
2108   // so now we copy the value out and into %rax/%eax.
2109   //
2110   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2111   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2112   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2113   // either case FuncInfo->setSRetReturnReg() will have been called.
2114   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2115     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2116            "No need for an sret register");
2117     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2118
2119     unsigned RetValReg
2120         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2121           X86::RAX : X86::EAX;
2122     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2123     Flag = Chain.getValue(1);
2124
2125     // RAX/EAX now acts like a return value.
2126     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2127   }
2128
2129   RetOps[0] = Chain;  // Update chain.
2130
2131   // Add the flag if we have it.
2132   if (Flag.getNode())
2133     RetOps.push_back(Flag);
2134
2135   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2136 }
2137
2138 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2139   if (N->getNumValues() != 1)
2140     return false;
2141   if (!N->hasNUsesOfValue(1, 0))
2142     return false;
2143
2144   SDValue TCChain = Chain;
2145   SDNode *Copy = *N->use_begin();
2146   if (Copy->getOpcode() == ISD::CopyToReg) {
2147     // If the copy has a glue operand, we conservatively assume it isn't safe to
2148     // perform a tail call.
2149     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2150       return false;
2151     TCChain = Copy->getOperand(0);
2152   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2153     return false;
2154
2155   bool HasRet = false;
2156   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2157        UI != UE; ++UI) {
2158     if (UI->getOpcode() != X86ISD::RET_FLAG)
2159       return false;
2160     // If we are returning more than one value, we can definitely
2161     // not make a tail call see PR19530
2162     if (UI->getNumOperands() > 4)
2163       return false;
2164     if (UI->getNumOperands() == 4 &&
2165         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2166       return false;
2167     HasRet = true;
2168   }
2169
2170   if (!HasRet)
2171     return false;
2172
2173   Chain = TCChain;
2174   return true;
2175 }
2176
2177 EVT
2178 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2179                                             ISD::NodeType ExtendKind) const {
2180   MVT ReturnMVT;
2181   // TODO: Is this also valid on 32-bit?
2182   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2183     ReturnMVT = MVT::i8;
2184   else
2185     ReturnMVT = MVT::i32;
2186
2187   EVT MinVT = getRegisterType(Context, ReturnMVT);
2188   return VT.bitsLT(MinVT) ? MinVT : VT;
2189 }
2190
2191 /// Lower the result values of a call into the
2192 /// appropriate copies out of appropriate physical registers.
2193 ///
2194 SDValue
2195 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2196                                    CallingConv::ID CallConv, bool isVarArg,
2197                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2198                                    SDLoc dl, SelectionDAG &DAG,
2199                                    SmallVectorImpl<SDValue> &InVals) const {
2200
2201   // Assign locations to each value returned by this call.
2202   SmallVector<CCValAssign, 16> RVLocs;
2203   bool Is64Bit = Subtarget->is64Bit();
2204   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2205                  *DAG.getContext());
2206   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2207
2208   // Copy all of the result registers out of their specified physreg.
2209   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2210     CCValAssign &VA = RVLocs[i];
2211     EVT CopyVT = VA.getValVT();
2212
2213     // If this is x86-64, and we disabled SSE, we can't return FP values
2214     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2215         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2216       report_fatal_error("SSE register return with SSE disabled");
2217     }
2218
2219     // If we prefer to use the value in xmm registers, copy it out as f80 and
2220     // use a truncate to move it from fp stack reg to xmm reg.
2221     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2222         isScalarFPTypeInSSEReg(VA.getValVT()))
2223       CopyVT = MVT::f80;
2224
2225     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2226                                CopyVT, InFlag).getValue(1);
2227     SDValue Val = Chain.getValue(0);
2228
2229     if (CopyVT != VA.getValVT())
2230       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2231                         // This truncation won't change the value.
2232                         DAG.getIntPtrConstant(1));
2233
2234     InFlag = Chain.getValue(2);
2235     InVals.push_back(Val);
2236   }
2237
2238   return Chain;
2239 }
2240
2241 //===----------------------------------------------------------------------===//
2242 //                C & StdCall & Fast Calling Convention implementation
2243 //===----------------------------------------------------------------------===//
2244 //  StdCall calling convention seems to be standard for many Windows' API
2245 //  routines and around. It differs from C calling convention just a little:
2246 //  callee should clean up the stack, not caller. Symbols should be also
2247 //  decorated in some fancy way :) It doesn't support any vector arguments.
2248 //  For info on fast calling convention see Fast Calling Convention (tail call)
2249 //  implementation LowerX86_32FastCCCallTo.
2250
2251 /// CallIsStructReturn - Determines whether a call uses struct return
2252 /// semantics.
2253 enum StructReturnType {
2254   NotStructReturn,
2255   RegStructReturn,
2256   StackStructReturn
2257 };
2258 static StructReturnType
2259 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2260   if (Outs.empty())
2261     return NotStructReturn;
2262
2263   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2264   if (!Flags.isSRet())
2265     return NotStructReturn;
2266   if (Flags.isInReg())
2267     return RegStructReturn;
2268   return StackStructReturn;
2269 }
2270
2271 /// Determines whether a function uses struct return semantics.
2272 static StructReturnType
2273 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2274   if (Ins.empty())
2275     return NotStructReturn;
2276
2277   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2278   if (!Flags.isSRet())
2279     return NotStructReturn;
2280   if (Flags.isInReg())
2281     return RegStructReturn;
2282   return StackStructReturn;
2283 }
2284
2285 /// Make a copy of an aggregate at address specified by "Src" to address
2286 /// "Dst" with size and alignment information specified by the specific
2287 /// parameter attribute. The copy will be passed as a byval function parameter.
2288 static SDValue
2289 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2290                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2291                           SDLoc dl) {
2292   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2293
2294   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2295                        /*isVolatile*/false, /*AlwaysInline=*/true,
2296                        MachinePointerInfo(), MachinePointerInfo());
2297 }
2298
2299 /// Return true if the calling convention is one that
2300 /// supports tail call optimization.
2301 static bool IsTailCallConvention(CallingConv::ID CC) {
2302   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2303           CC == CallingConv::HiPE);
2304 }
2305
2306 /// \brief Return true if the calling convention is a C calling convention.
2307 static bool IsCCallConvention(CallingConv::ID CC) {
2308   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2309           CC == CallingConv::X86_64_SysV);
2310 }
2311
2312 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2313   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2314     return false;
2315
2316   CallSite CS(CI);
2317   CallingConv::ID CalleeCC = CS.getCallingConv();
2318   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2319     return false;
2320
2321   return true;
2322 }
2323
2324 /// Return true if the function is being made into
2325 /// a tailcall target by changing its ABI.
2326 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2327                                    bool GuaranteedTailCallOpt) {
2328   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2329 }
2330
2331 SDValue
2332 X86TargetLowering::LowerMemArgument(SDValue Chain,
2333                                     CallingConv::ID CallConv,
2334                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2335                                     SDLoc dl, SelectionDAG &DAG,
2336                                     const CCValAssign &VA,
2337                                     MachineFrameInfo *MFI,
2338                                     unsigned i) const {
2339   // Create the nodes corresponding to a load from this parameter slot.
2340   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2341   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2342       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2343   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2344   EVT ValVT;
2345
2346   // If value is passed by pointer we have address passed instead of the value
2347   // itself.
2348   if (VA.getLocInfo() == CCValAssign::Indirect)
2349     ValVT = VA.getLocVT();
2350   else
2351     ValVT = VA.getValVT();
2352
2353   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2354   // changed with more analysis.
2355   // In case of tail call optimization mark all arguments mutable. Since they
2356   // could be overwritten by lowering of arguments in case of a tail call.
2357   if (Flags.isByVal()) {
2358     unsigned Bytes = Flags.getByValSize();
2359     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2360     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2361     return DAG.getFrameIndex(FI, getPointerTy());
2362   } else {
2363     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2364                                     VA.getLocMemOffset(), isImmutable);
2365     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2366     return DAG.getLoad(ValVT, dl, Chain, FIN,
2367                        MachinePointerInfo::getFixedStack(FI),
2368                        false, false, false, 0);
2369   }
2370 }
2371
2372 // FIXME: Get this from tablegen.
2373 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2374                                                 const X86Subtarget *Subtarget) {
2375   assert(Subtarget->is64Bit());
2376
2377   if (Subtarget->isCallingConvWin64(CallConv)) {
2378     static const MCPhysReg GPR64ArgRegsWin64[] = {
2379       X86::RCX, X86::RDX, X86::R8,  X86::R9
2380     };
2381     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2382   }
2383
2384   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2385     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2386   };
2387   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2388 }
2389
2390 // FIXME: Get this from tablegen.
2391 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2392                                                 CallingConv::ID CallConv,
2393                                                 const X86Subtarget *Subtarget) {
2394   assert(Subtarget->is64Bit());
2395   if (Subtarget->isCallingConvWin64(CallConv)) {
2396     // The XMM registers which might contain var arg parameters are shadowed
2397     // in their paired GPR.  So we only need to save the GPR to their home
2398     // slots.
2399     // TODO: __vectorcall will change this.
2400     return None;
2401   }
2402
2403   const Function *Fn = MF.getFunction();
2404   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2405   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2406          "SSE register cannot be used when SSE is disabled!");
2407   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2408       !Subtarget->hasSSE1())
2409     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2410     // registers.
2411     return None;
2412
2413   static const MCPhysReg XMMArgRegs64Bit[] = {
2414     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2415     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2416   };
2417   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2418 }
2419
2420 SDValue
2421 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2422                                         CallingConv::ID CallConv,
2423                                         bool isVarArg,
2424                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2425                                         SDLoc dl,
2426                                         SelectionDAG &DAG,
2427                                         SmallVectorImpl<SDValue> &InVals)
2428                                           const {
2429   MachineFunction &MF = DAG.getMachineFunction();
2430   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2431
2432   const Function* Fn = MF.getFunction();
2433   if (Fn->hasExternalLinkage() &&
2434       Subtarget->isTargetCygMing() &&
2435       Fn->getName() == "main")
2436     FuncInfo->setForceFramePointer(true);
2437
2438   MachineFrameInfo *MFI = MF.getFrameInfo();
2439   bool Is64Bit = Subtarget->is64Bit();
2440   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2441
2442   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2443          "Var args not supported with calling convention fastcc, ghc or hipe");
2444
2445   // Assign locations to all of the incoming arguments.
2446   SmallVector<CCValAssign, 16> ArgLocs;
2447   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2448
2449   // Allocate shadow area for Win64
2450   if (IsWin64)
2451     CCInfo.AllocateStack(32, 8);
2452
2453   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2454
2455   unsigned LastVal = ~0U;
2456   SDValue ArgValue;
2457   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2458     CCValAssign &VA = ArgLocs[i];
2459     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2460     // places.
2461     assert(VA.getValNo() != LastVal &&
2462            "Don't support value assigned to multiple locs yet");
2463     (void)LastVal;
2464     LastVal = VA.getValNo();
2465
2466     if (VA.isRegLoc()) {
2467       EVT RegVT = VA.getLocVT();
2468       const TargetRegisterClass *RC;
2469       if (RegVT == MVT::i32)
2470         RC = &X86::GR32RegClass;
2471       else if (Is64Bit && RegVT == MVT::i64)
2472         RC = &X86::GR64RegClass;
2473       else if (RegVT == MVT::f32)
2474         RC = &X86::FR32RegClass;
2475       else if (RegVT == MVT::f64)
2476         RC = &X86::FR64RegClass;
2477       else if (RegVT.is512BitVector())
2478         RC = &X86::VR512RegClass;
2479       else if (RegVT.is256BitVector())
2480         RC = &X86::VR256RegClass;
2481       else if (RegVT.is128BitVector())
2482         RC = &X86::VR128RegClass;
2483       else if (RegVT == MVT::x86mmx)
2484         RC = &X86::VR64RegClass;
2485       else if (RegVT == MVT::i1)
2486         RC = &X86::VK1RegClass;
2487       else if (RegVT == MVT::v8i1)
2488         RC = &X86::VK8RegClass;
2489       else if (RegVT == MVT::v16i1)
2490         RC = &X86::VK16RegClass;
2491       else if (RegVT == MVT::v32i1)
2492         RC = &X86::VK32RegClass;
2493       else if (RegVT == MVT::v64i1)
2494         RC = &X86::VK64RegClass;
2495       else
2496         llvm_unreachable("Unknown argument type!");
2497
2498       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2499       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2500
2501       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2502       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2503       // right size.
2504       if (VA.getLocInfo() == CCValAssign::SExt)
2505         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2506                                DAG.getValueType(VA.getValVT()));
2507       else if (VA.getLocInfo() == CCValAssign::ZExt)
2508         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2509                                DAG.getValueType(VA.getValVT()));
2510       else if (VA.getLocInfo() == CCValAssign::BCvt)
2511         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2512
2513       if (VA.isExtInLoc()) {
2514         // Handle MMX values passed in XMM regs.
2515         if (RegVT.isVector())
2516           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2517         else
2518           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2519       }
2520     } else {
2521       assert(VA.isMemLoc());
2522       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2523     }
2524
2525     // If value is passed via pointer - do a load.
2526     if (VA.getLocInfo() == CCValAssign::Indirect)
2527       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2528                              MachinePointerInfo(), false, false, false, 0);
2529
2530     InVals.push_back(ArgValue);
2531   }
2532
2533   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2534     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2535       // The x86-64 ABIs require that for returning structs by value we copy
2536       // the sret argument into %rax/%eax (depending on ABI) for the return.
2537       // Win32 requires us to put the sret argument to %eax as well.
2538       // Save the argument into a virtual register so that we can access it
2539       // from the return points.
2540       if (Ins[i].Flags.isSRet()) {
2541         unsigned Reg = FuncInfo->getSRetReturnReg();
2542         if (!Reg) {
2543           MVT PtrTy = getPointerTy();
2544           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2545           FuncInfo->setSRetReturnReg(Reg);
2546         }
2547         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2548         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2549         break;
2550       }
2551     }
2552   }
2553
2554   unsigned StackSize = CCInfo.getNextStackOffset();
2555   // Align stack specially for tail calls.
2556   if (FuncIsMadeTailCallSafe(CallConv,
2557                              MF.getTarget().Options.GuaranteedTailCallOpt))
2558     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2559
2560   // If the function takes variable number of arguments, make a frame index for
2561   // the start of the first vararg value... for expansion of llvm.va_start. We
2562   // can skip this if there are no va_start calls.
2563   if (MFI->hasVAStart() &&
2564       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2565                    CallConv != CallingConv::X86_ThisCall))) {
2566     FuncInfo->setVarArgsFrameIndex(
2567         MFI->CreateFixedObject(1, StackSize, true));
2568   }
2569
2570   // Figure out if XMM registers are in use.
2571   assert(!(MF.getTarget().Options.UseSoftFloat &&
2572            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2573          "SSE register cannot be used when SSE is disabled!");
2574
2575   // 64-bit calling conventions support varargs and register parameters, so we
2576   // have to do extra work to spill them in the prologue.
2577   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2578     // Find the first unallocated argument registers.
2579     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2580     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2581     unsigned NumIntRegs =
2582         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2583     unsigned NumXMMRegs =
2584         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2585     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2586            "SSE register cannot be used when SSE is disabled!");
2587
2588     // Gather all the live in physical registers.
2589     SmallVector<SDValue, 6> LiveGPRs;
2590     SmallVector<SDValue, 8> LiveXMMRegs;
2591     SDValue ALVal;
2592     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2593       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2594       LiveGPRs.push_back(
2595           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2596     }
2597     if (!ArgXMMs.empty()) {
2598       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2599       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2600       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2601         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2602         LiveXMMRegs.push_back(
2603             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2604       }
2605     }
2606
2607     if (IsWin64) {
2608       const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2609       // Get to the caller-allocated home save location.  Add 8 to account
2610       // for the return address.
2611       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2612       FuncInfo->setRegSaveFrameIndex(
2613           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2614       // Fixup to set vararg frame on shadow area (4 x i64).
2615       if (NumIntRegs < 4)
2616         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2617     } else {
2618       // For X86-64, if there are vararg parameters that are passed via
2619       // registers, then we must store them to their spots on the stack so
2620       // they may be loaded by deferencing the result of va_next.
2621       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2622       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2623       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2624           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2625     }
2626
2627     // Store the integer parameter registers.
2628     SmallVector<SDValue, 8> MemOps;
2629     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2630                                       getPointerTy());
2631     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2632     for (SDValue Val : LiveGPRs) {
2633       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2634                                 DAG.getIntPtrConstant(Offset));
2635       SDValue Store =
2636         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2637                      MachinePointerInfo::getFixedStack(
2638                        FuncInfo->getRegSaveFrameIndex(), Offset),
2639                      false, false, 0);
2640       MemOps.push_back(Store);
2641       Offset += 8;
2642     }
2643
2644     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2645       // Now store the XMM (fp + vector) parameter registers.
2646       SmallVector<SDValue, 12> SaveXMMOps;
2647       SaveXMMOps.push_back(Chain);
2648       SaveXMMOps.push_back(ALVal);
2649       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2650                              FuncInfo->getRegSaveFrameIndex()));
2651       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2652                              FuncInfo->getVarArgsFPOffset()));
2653       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2654                         LiveXMMRegs.end());
2655       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2656                                    MVT::Other, SaveXMMOps));
2657     }
2658
2659     if (!MemOps.empty())
2660       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2661   }
2662
2663   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2664     // Find the largest legal vector type.
2665     MVT VecVT = MVT::Other;
2666     // FIXME: Only some x86_32 calling conventions support AVX512.
2667     if (Subtarget->hasAVX512() &&
2668         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2669                      CallConv == CallingConv::Intel_OCL_BI)))
2670       VecVT = MVT::v16f32;
2671     else if (Subtarget->hasAVX())
2672       VecVT = MVT::v8f32;
2673     else if (Subtarget->hasSSE2())
2674       VecVT = MVT::v4f32;
2675
2676     // We forward some GPRs and some vector types.
2677     SmallVector<MVT, 2> RegParmTypes;
2678     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2679     RegParmTypes.push_back(IntVT);
2680     if (VecVT != MVT::Other)
2681       RegParmTypes.push_back(VecVT);
2682
2683     // Compute the set of forwarded registers. The rest are scratch.
2684     SmallVectorImpl<ForwardedRegister> &Forwards =
2685         FuncInfo->getForwardedMustTailRegParms();
2686     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2687
2688     // Conservatively forward AL on x86_64, since it might be used for varargs.
2689     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2690       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2691       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2692     }
2693
2694     // Copy all forwards from physical to virtual registers.
2695     for (ForwardedRegister &F : Forwards) {
2696       // FIXME: Can we use a less constrained schedule?
2697       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2698       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2699       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2700     }
2701   }
2702
2703   // Some CCs need callee pop.
2704   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2705                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2706     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2707   } else {
2708     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2709     // If this is an sret function, the return should pop the hidden pointer.
2710     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2711         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2712         argsAreStructReturn(Ins) == StackStructReturn)
2713       FuncInfo->setBytesToPopOnReturn(4);
2714   }
2715
2716   if (!Is64Bit) {
2717     // RegSaveFrameIndex is X86-64 only.
2718     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2719     if (CallConv == CallingConv::X86_FastCall ||
2720         CallConv == CallingConv::X86_ThisCall)
2721       // fastcc functions can't have varargs.
2722       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2723   }
2724
2725   FuncInfo->setArgumentStackSize(StackSize);
2726
2727   return Chain;
2728 }
2729
2730 SDValue
2731 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2732                                     SDValue StackPtr, SDValue Arg,
2733                                     SDLoc dl, SelectionDAG &DAG,
2734                                     const CCValAssign &VA,
2735                                     ISD::ArgFlagsTy Flags) const {
2736   unsigned LocMemOffset = VA.getLocMemOffset();
2737   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2738   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2739   if (Flags.isByVal())
2740     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2741
2742   return DAG.getStore(Chain, dl, Arg, PtrOff,
2743                       MachinePointerInfo::getStack(LocMemOffset),
2744                       false, false, 0);
2745 }
2746
2747 /// Emit a load of return address if tail call
2748 /// optimization is performed and it is required.
2749 SDValue
2750 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2751                                            SDValue &OutRetAddr, SDValue Chain,
2752                                            bool IsTailCall, bool Is64Bit,
2753                                            int FPDiff, SDLoc dl) const {
2754   // Adjust the Return address stack slot.
2755   EVT VT = getPointerTy();
2756   OutRetAddr = getReturnAddressFrameIndex(DAG);
2757
2758   // Load the "old" Return address.
2759   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2760                            false, false, false, 0);
2761   return SDValue(OutRetAddr.getNode(), 1);
2762 }
2763
2764 /// Emit a store of the return address if tail call
2765 /// optimization is performed and it is required (FPDiff!=0).
2766 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2767                                         SDValue Chain, SDValue RetAddrFrIdx,
2768                                         EVT PtrVT, unsigned SlotSize,
2769                                         int FPDiff, SDLoc dl) {
2770   // Store the return address to the appropriate stack slot.
2771   if (!FPDiff) return Chain;
2772   // Calculate the new stack slot for the return address.
2773   int NewReturnAddrFI =
2774     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2775                                          false);
2776   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2777   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2778                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2779                        false, false, 0);
2780   return Chain;
2781 }
2782
2783 SDValue
2784 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2785                              SmallVectorImpl<SDValue> &InVals) const {
2786   SelectionDAG &DAG                     = CLI.DAG;
2787   SDLoc &dl                             = CLI.DL;
2788   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2789   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2790   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2791   SDValue Chain                         = CLI.Chain;
2792   SDValue Callee                        = CLI.Callee;
2793   CallingConv::ID CallConv              = CLI.CallConv;
2794   bool &isTailCall                      = CLI.IsTailCall;
2795   bool isVarArg                         = CLI.IsVarArg;
2796
2797   MachineFunction &MF = DAG.getMachineFunction();
2798   bool Is64Bit        = Subtarget->is64Bit();
2799   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2800   StructReturnType SR = callIsStructReturn(Outs);
2801   bool IsSibcall      = false;
2802   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2803
2804   if (MF.getTarget().Options.DisableTailCalls)
2805     isTailCall = false;
2806
2807   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2808   if (IsMustTail) {
2809     // Force this to be a tail call.  The verifier rules are enough to ensure
2810     // that we can lower this successfully without moving the return address
2811     // around.
2812     isTailCall = true;
2813   } else if (isTailCall) {
2814     // Check if it's really possible to do a tail call.
2815     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2816                     isVarArg, SR != NotStructReturn,
2817                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2818                     Outs, OutVals, Ins, DAG);
2819
2820     // Sibcalls are automatically detected tailcalls which do not require
2821     // ABI changes.
2822     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2823       IsSibcall = true;
2824
2825     if (isTailCall)
2826       ++NumTailCalls;
2827   }
2828
2829   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2830          "Var args not supported with calling convention fastcc, ghc or hipe");
2831
2832   // Analyze operands of the call, assigning locations to each operand.
2833   SmallVector<CCValAssign, 16> ArgLocs;
2834   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2835
2836   // Allocate shadow area for Win64
2837   if (IsWin64)
2838     CCInfo.AllocateStack(32, 8);
2839
2840   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2841
2842   // Get a count of how many bytes are to be pushed on the stack.
2843   unsigned NumBytes = CCInfo.getNextStackOffset();
2844   if (IsSibcall)
2845     // This is a sibcall. The memory operands are available in caller's
2846     // own caller's stack.
2847     NumBytes = 0;
2848   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2849            IsTailCallConvention(CallConv))
2850     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2851
2852   int FPDiff = 0;
2853   if (isTailCall && !IsSibcall && !IsMustTail) {
2854     // Lower arguments at fp - stackoffset + fpdiff.
2855     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2856
2857     FPDiff = NumBytesCallerPushed - NumBytes;
2858
2859     // Set the delta of movement of the returnaddr stackslot.
2860     // But only set if delta is greater than previous delta.
2861     if (FPDiff < X86Info->getTCReturnAddrDelta())
2862       X86Info->setTCReturnAddrDelta(FPDiff);
2863   }
2864
2865   unsigned NumBytesToPush = NumBytes;
2866   unsigned NumBytesToPop = NumBytes;
2867
2868   // If we have an inalloca argument, all stack space has already been allocated
2869   // for us and be right at the top of the stack.  We don't support multiple
2870   // arguments passed in memory when using inalloca.
2871   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2872     NumBytesToPush = 0;
2873     if (!ArgLocs.back().isMemLoc())
2874       report_fatal_error("cannot use inalloca attribute on a register "
2875                          "parameter");
2876     if (ArgLocs.back().getLocMemOffset() != 0)
2877       report_fatal_error("any parameter with the inalloca attribute must be "
2878                          "the only memory argument");
2879   }
2880
2881   if (!IsSibcall)
2882     Chain = DAG.getCALLSEQ_START(
2883         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2884
2885   SDValue RetAddrFrIdx;
2886   // Load return address for tail calls.
2887   if (isTailCall && FPDiff)
2888     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2889                                     Is64Bit, FPDiff, dl);
2890
2891   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2892   SmallVector<SDValue, 8> MemOpChains;
2893   SDValue StackPtr;
2894
2895   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2896   // of tail call optimization arguments are handle later.
2897   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2898   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2899     // Skip inalloca arguments, they have already been written.
2900     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2901     if (Flags.isInAlloca())
2902       continue;
2903
2904     CCValAssign &VA = ArgLocs[i];
2905     EVT RegVT = VA.getLocVT();
2906     SDValue Arg = OutVals[i];
2907     bool isByVal = Flags.isByVal();
2908
2909     // Promote the value if needed.
2910     switch (VA.getLocInfo()) {
2911     default: llvm_unreachable("Unknown loc info!");
2912     case CCValAssign::Full: break;
2913     case CCValAssign::SExt:
2914       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2915       break;
2916     case CCValAssign::ZExt:
2917       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2918       break;
2919     case CCValAssign::AExt:
2920       if (RegVT.is128BitVector()) {
2921         // Special case: passing MMX values in XMM registers.
2922         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2923         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2924         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2925       } else
2926         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2927       break;
2928     case CCValAssign::BCvt:
2929       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2930       break;
2931     case CCValAssign::Indirect: {
2932       // Store the argument.
2933       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2934       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2935       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2936                            MachinePointerInfo::getFixedStack(FI),
2937                            false, false, 0);
2938       Arg = SpillSlot;
2939       break;
2940     }
2941     }
2942
2943     if (VA.isRegLoc()) {
2944       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2945       if (isVarArg && IsWin64) {
2946         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2947         // shadow reg if callee is a varargs function.
2948         unsigned ShadowReg = 0;
2949         switch (VA.getLocReg()) {
2950         case X86::XMM0: ShadowReg = X86::RCX; break;
2951         case X86::XMM1: ShadowReg = X86::RDX; break;
2952         case X86::XMM2: ShadowReg = X86::R8; break;
2953         case X86::XMM3: ShadowReg = X86::R9; break;
2954         }
2955         if (ShadowReg)
2956           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2957       }
2958     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2959       assert(VA.isMemLoc());
2960       if (!StackPtr.getNode())
2961         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2962                                       getPointerTy());
2963       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2964                                              dl, DAG, VA, Flags));
2965     }
2966   }
2967
2968   if (!MemOpChains.empty())
2969     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2970
2971   if (Subtarget->isPICStyleGOT()) {
2972     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2973     // GOT pointer.
2974     if (!isTailCall) {
2975       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2976                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2977     } else {
2978       // If we are tail calling and generating PIC/GOT style code load the
2979       // address of the callee into ECX. The value in ecx is used as target of
2980       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2981       // for tail calls on PIC/GOT architectures. Normally we would just put the
2982       // address of GOT into ebx and then call target@PLT. But for tail calls
2983       // ebx would be restored (since ebx is callee saved) before jumping to the
2984       // target@PLT.
2985
2986       // Note: The actual moving to ECX is done further down.
2987       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2988       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2989           !G->getGlobal()->hasProtectedVisibility())
2990         Callee = LowerGlobalAddress(Callee, DAG);
2991       else if (isa<ExternalSymbolSDNode>(Callee))
2992         Callee = LowerExternalSymbol(Callee, DAG);
2993     }
2994   }
2995
2996   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2997     // From AMD64 ABI document:
2998     // For calls that may call functions that use varargs or stdargs
2999     // (prototype-less calls or calls to functions containing ellipsis (...) in
3000     // the declaration) %al is used as hidden argument to specify the number
3001     // of SSE registers used. The contents of %al do not need to match exactly
3002     // the number of registers, but must be an ubound on the number of SSE
3003     // registers used and is in the range 0 - 8 inclusive.
3004
3005     // Count the number of XMM registers allocated.
3006     static const MCPhysReg XMMArgRegs[] = {
3007       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3008       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3009     };
3010     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
3011     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3012            && "SSE registers cannot be used when SSE is disabled");
3013
3014     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3015                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
3016   }
3017
3018   if (isVarArg && IsMustTail) {
3019     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3020     for (const auto &F : Forwards) {
3021       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3022       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3023     }
3024   }
3025
3026   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3027   // don't need this because the eligibility check rejects calls that require
3028   // shuffling arguments passed in memory.
3029   if (!IsSibcall && isTailCall) {
3030     // Force all the incoming stack arguments to be loaded from the stack
3031     // before any new outgoing arguments are stored to the stack, because the
3032     // outgoing stack slots may alias the incoming argument stack slots, and
3033     // the alias isn't otherwise explicit. This is slightly more conservative
3034     // than necessary, because it means that each store effectively depends
3035     // on every argument instead of just those arguments it would clobber.
3036     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3037
3038     SmallVector<SDValue, 8> MemOpChains2;
3039     SDValue FIN;
3040     int FI = 0;
3041     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3042       CCValAssign &VA = ArgLocs[i];
3043       if (VA.isRegLoc())
3044         continue;
3045       assert(VA.isMemLoc());
3046       SDValue Arg = OutVals[i];
3047       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3048       // Skip inalloca arguments.  They don't require any work.
3049       if (Flags.isInAlloca())
3050         continue;
3051       // Create frame index.
3052       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3053       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3054       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3055       FIN = DAG.getFrameIndex(FI, getPointerTy());
3056
3057       if (Flags.isByVal()) {
3058         // Copy relative to framepointer.
3059         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3060         if (!StackPtr.getNode())
3061           StackPtr = DAG.getCopyFromReg(Chain, dl,
3062                                         RegInfo->getStackRegister(),
3063                                         getPointerTy());
3064         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3065
3066         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3067                                                          ArgChain,
3068                                                          Flags, DAG, dl));
3069       } else {
3070         // Store relative to framepointer.
3071         MemOpChains2.push_back(
3072           DAG.getStore(ArgChain, dl, Arg, FIN,
3073                        MachinePointerInfo::getFixedStack(FI),
3074                        false, false, 0));
3075       }
3076     }
3077
3078     if (!MemOpChains2.empty())
3079       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3080
3081     // Store the return address to the appropriate stack slot.
3082     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3083                                      getPointerTy(), RegInfo->getSlotSize(),
3084                                      FPDiff, dl);
3085   }
3086
3087   // Build a sequence of copy-to-reg nodes chained together with token chain
3088   // and flag operands which copy the outgoing args into registers.
3089   SDValue InFlag;
3090   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3091     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3092                              RegsToPass[i].second, InFlag);
3093     InFlag = Chain.getValue(1);
3094   }
3095
3096   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3097     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3098     // In the 64-bit large code model, we have to make all calls
3099     // through a register, since the call instruction's 32-bit
3100     // pc-relative offset may not be large enough to hold the whole
3101     // address.
3102   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3103     // If the callee is a GlobalAddress node (quite common, every direct call
3104     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3105     // it.
3106     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3107
3108     // We should use extra load for direct calls to dllimported functions in
3109     // non-JIT mode.
3110     const GlobalValue *GV = G->getGlobal();
3111     if (!GV->hasDLLImportStorageClass()) {
3112       unsigned char OpFlags = 0;
3113       bool ExtraLoad = false;
3114       unsigned WrapperKind = ISD::DELETED_NODE;
3115
3116       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3117       // external symbols most go through the PLT in PIC mode.  If the symbol
3118       // has hidden or protected visibility, or if it is static or local, then
3119       // we don't need to use the PLT - we can directly call it.
3120       if (Subtarget->isTargetELF() &&
3121           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3122           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3123         OpFlags = X86II::MO_PLT;
3124       } else if (Subtarget->isPICStyleStubAny() &&
3125                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3126                  (!Subtarget->getTargetTriple().isMacOSX() ||
3127                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3128         // PC-relative references to external symbols should go through $stub,
3129         // unless we're building with the leopard linker or later, which
3130         // automatically synthesizes these stubs.
3131         OpFlags = X86II::MO_DARWIN_STUB;
3132       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3133                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3134         // If the function is marked as non-lazy, generate an indirect call
3135         // which loads from the GOT directly. This avoids runtime overhead
3136         // at the cost of eager binding (and one extra byte of encoding).
3137         OpFlags = X86II::MO_GOTPCREL;
3138         WrapperKind = X86ISD::WrapperRIP;
3139         ExtraLoad = true;
3140       }
3141
3142       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3143                                           G->getOffset(), OpFlags);
3144
3145       // Add a wrapper if needed.
3146       if (WrapperKind != ISD::DELETED_NODE)
3147         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3148       // Add extra indirection if needed.
3149       if (ExtraLoad)
3150         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3151                              MachinePointerInfo::getGOT(),
3152                              false, false, false, 0);
3153     }
3154   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3155     unsigned char OpFlags = 0;
3156
3157     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3158     // external symbols should go through the PLT.
3159     if (Subtarget->isTargetELF() &&
3160         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3161       OpFlags = X86II::MO_PLT;
3162     } else if (Subtarget->isPICStyleStubAny() &&
3163                (!Subtarget->getTargetTriple().isMacOSX() ||
3164                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3165       // PC-relative references to external symbols should go through $stub,
3166       // unless we're building with the leopard linker or later, which
3167       // automatically synthesizes these stubs.
3168       OpFlags = X86II::MO_DARWIN_STUB;
3169     }
3170
3171     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3172                                          OpFlags);
3173   } else if (Subtarget->isTarget64BitILP32() &&
3174              Callee->getValueType(0) == MVT::i32) {
3175     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3176     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3177   }
3178
3179   // Returns a chain & a flag for retval copy to use.
3180   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3181   SmallVector<SDValue, 8> Ops;
3182
3183   if (!IsSibcall && isTailCall) {
3184     Chain = DAG.getCALLSEQ_END(Chain,
3185                                DAG.getIntPtrConstant(NumBytesToPop, true),
3186                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3187     InFlag = Chain.getValue(1);
3188   }
3189
3190   Ops.push_back(Chain);
3191   Ops.push_back(Callee);
3192
3193   if (isTailCall)
3194     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3195
3196   // Add argument registers to the end of the list so that they are known live
3197   // into the call.
3198   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3199     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3200                                   RegsToPass[i].second.getValueType()));
3201
3202   // Add a register mask operand representing the call-preserved registers.
3203   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3204   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3205   assert(Mask && "Missing call preserved mask for calling convention");
3206   Ops.push_back(DAG.getRegisterMask(Mask));
3207
3208   if (InFlag.getNode())
3209     Ops.push_back(InFlag);
3210
3211   if (isTailCall) {
3212     // We used to do:
3213     //// If this is the first return lowered for this function, add the regs
3214     //// to the liveout set for the function.
3215     // This isn't right, although it's probably harmless on x86; liveouts
3216     // should be computed from returns not tail calls.  Consider a void
3217     // function making a tail call to a function returning int.
3218     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3219   }
3220
3221   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3222   InFlag = Chain.getValue(1);
3223
3224   // Create the CALLSEQ_END node.
3225   unsigned NumBytesForCalleeToPop;
3226   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3227                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3228     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3229   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3230            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3231            SR == StackStructReturn)
3232     // If this is a call to a struct-return function, the callee
3233     // pops the hidden struct pointer, so we have to push it back.
3234     // This is common for Darwin/X86, Linux & Mingw32 targets.
3235     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3236     NumBytesForCalleeToPop = 4;
3237   else
3238     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3239
3240   // Returns a flag for retval copy to use.
3241   if (!IsSibcall) {
3242     Chain = DAG.getCALLSEQ_END(Chain,
3243                                DAG.getIntPtrConstant(NumBytesToPop, true),
3244                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3245                                                      true),
3246                                InFlag, dl);
3247     InFlag = Chain.getValue(1);
3248   }
3249
3250   // Handle result values, copying them out of physregs into vregs that we
3251   // return.
3252   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3253                          Ins, dl, DAG, InVals);
3254 }
3255
3256 //===----------------------------------------------------------------------===//
3257 //                Fast Calling Convention (tail call) implementation
3258 //===----------------------------------------------------------------------===//
3259
3260 //  Like std call, callee cleans arguments, convention except that ECX is
3261 //  reserved for storing the tail called function address. Only 2 registers are
3262 //  free for argument passing (inreg). Tail call optimization is performed
3263 //  provided:
3264 //                * tailcallopt is enabled
3265 //                * caller/callee are fastcc
3266 //  On X86_64 architecture with GOT-style position independent code only local
3267 //  (within module) calls are supported at the moment.
3268 //  To keep the stack aligned according to platform abi the function
3269 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3270 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3271 //  If a tail called function callee has more arguments than the caller the
3272 //  caller needs to make sure that there is room to move the RETADDR to. This is
3273 //  achieved by reserving an area the size of the argument delta right after the
3274 //  original RETADDR, but before the saved framepointer or the spilled registers
3275 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3276 //  stack layout:
3277 //    arg1
3278 //    arg2
3279 //    RETADDR
3280 //    [ new RETADDR
3281 //      move area ]
3282 //    (possible EBP)
3283 //    ESI
3284 //    EDI
3285 //    local1 ..
3286
3287 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3288 /// for a 16 byte align requirement.
3289 unsigned
3290 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3291                                                SelectionDAG& DAG) const {
3292   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3293   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3294   unsigned StackAlignment = TFI.getStackAlignment();
3295   uint64_t AlignMask = StackAlignment - 1;
3296   int64_t Offset = StackSize;
3297   unsigned SlotSize = RegInfo->getSlotSize();
3298   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3299     // Number smaller than 12 so just add the difference.
3300     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3301   } else {
3302     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3303     Offset = ((~AlignMask) & Offset) + StackAlignment +
3304       (StackAlignment-SlotSize);
3305   }
3306   return Offset;
3307 }
3308
3309 /// MatchingStackOffset - Return true if the given stack call argument is
3310 /// already available in the same position (relatively) of the caller's
3311 /// incoming argument stack.
3312 static
3313 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3314                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3315                          const X86InstrInfo *TII) {
3316   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3317   int FI = INT_MAX;
3318   if (Arg.getOpcode() == ISD::CopyFromReg) {
3319     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3320     if (!TargetRegisterInfo::isVirtualRegister(VR))
3321       return false;
3322     MachineInstr *Def = MRI->getVRegDef(VR);
3323     if (!Def)
3324       return false;
3325     if (!Flags.isByVal()) {
3326       if (!TII->isLoadFromStackSlot(Def, FI))
3327         return false;
3328     } else {
3329       unsigned Opcode = Def->getOpcode();
3330       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3331            Opcode == X86::LEA64_32r) &&
3332           Def->getOperand(1).isFI()) {
3333         FI = Def->getOperand(1).getIndex();
3334         Bytes = Flags.getByValSize();
3335       } else
3336         return false;
3337     }
3338   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3339     if (Flags.isByVal())
3340       // ByVal argument is passed in as a pointer but it's now being
3341       // dereferenced. e.g.
3342       // define @foo(%struct.X* %A) {
3343       //   tail call @bar(%struct.X* byval %A)
3344       // }
3345       return false;
3346     SDValue Ptr = Ld->getBasePtr();
3347     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3348     if (!FINode)
3349       return false;
3350     FI = FINode->getIndex();
3351   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3352     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3353     FI = FINode->getIndex();
3354     Bytes = Flags.getByValSize();
3355   } else
3356     return false;
3357
3358   assert(FI != INT_MAX);
3359   if (!MFI->isFixedObjectIndex(FI))
3360     return false;
3361   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3362 }
3363
3364 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3365 /// for tail call optimization. Targets which want to do tail call
3366 /// optimization should implement this function.
3367 bool
3368 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3369                                                      CallingConv::ID CalleeCC,
3370                                                      bool isVarArg,
3371                                                      bool isCalleeStructRet,
3372                                                      bool isCallerStructRet,
3373                                                      Type *RetTy,
3374                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3375                                     const SmallVectorImpl<SDValue> &OutVals,
3376                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3377                                                      SelectionDAG &DAG) const {
3378   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3379     return false;
3380
3381   // If -tailcallopt is specified, make fastcc functions tail-callable.
3382   const MachineFunction &MF = DAG.getMachineFunction();
3383   const Function *CallerF = MF.getFunction();
3384
3385   // If the function return type is x86_fp80 and the callee return type is not,
3386   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3387   // perform a tailcall optimization here.
3388   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3389     return false;
3390
3391   CallingConv::ID CallerCC = CallerF->getCallingConv();
3392   bool CCMatch = CallerCC == CalleeCC;
3393   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3394   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3395
3396   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3397     if (IsTailCallConvention(CalleeCC) && CCMatch)
3398       return true;
3399     return false;
3400   }
3401
3402   // Look for obvious safe cases to perform tail call optimization that do not
3403   // require ABI changes. This is what gcc calls sibcall.
3404
3405   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3406   // emit a special epilogue.
3407   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3408   if (RegInfo->needsStackRealignment(MF))
3409     return false;
3410
3411   // Also avoid sibcall optimization if either caller or callee uses struct
3412   // return semantics.
3413   if (isCalleeStructRet || isCallerStructRet)
3414     return false;
3415
3416   // An stdcall/thiscall caller is expected to clean up its arguments; the
3417   // callee isn't going to do that.
3418   // FIXME: this is more restrictive than needed. We could produce a tailcall
3419   // when the stack adjustment matches. For example, with a thiscall that takes
3420   // only one argument.
3421   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3422                    CallerCC == CallingConv::X86_ThisCall))
3423     return false;
3424
3425   // Do not sibcall optimize vararg calls unless all arguments are passed via
3426   // registers.
3427   if (isVarArg && !Outs.empty()) {
3428
3429     // Optimizing for varargs on Win64 is unlikely to be safe without
3430     // additional testing.
3431     if (IsCalleeWin64 || IsCallerWin64)
3432       return false;
3433
3434     SmallVector<CCValAssign, 16> ArgLocs;
3435     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3436                    *DAG.getContext());
3437
3438     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3439     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3440       if (!ArgLocs[i].isRegLoc())
3441         return false;
3442   }
3443
3444   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3445   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3446   // this into a sibcall.
3447   bool Unused = false;
3448   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3449     if (!Ins[i].Used) {
3450       Unused = true;
3451       break;
3452     }
3453   }
3454   if (Unused) {
3455     SmallVector<CCValAssign, 16> RVLocs;
3456     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3457                    *DAG.getContext());
3458     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3459     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3460       CCValAssign &VA = RVLocs[i];
3461       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3462         return false;
3463     }
3464   }
3465
3466   // If the calling conventions do not match, then we'd better make sure the
3467   // results are returned in the same way as what the caller expects.
3468   if (!CCMatch) {
3469     SmallVector<CCValAssign, 16> RVLocs1;
3470     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3471                     *DAG.getContext());
3472     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3473
3474     SmallVector<CCValAssign, 16> RVLocs2;
3475     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3476                     *DAG.getContext());
3477     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3478
3479     if (RVLocs1.size() != RVLocs2.size())
3480       return false;
3481     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3482       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3483         return false;
3484       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3485         return false;
3486       if (RVLocs1[i].isRegLoc()) {
3487         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3488           return false;
3489       } else {
3490         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3491           return false;
3492       }
3493     }
3494   }
3495
3496   // If the callee takes no arguments then go on to check the results of the
3497   // call.
3498   if (!Outs.empty()) {
3499     // Check if stack adjustment is needed. For now, do not do this if any
3500     // argument is passed on the stack.
3501     SmallVector<CCValAssign, 16> ArgLocs;
3502     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3503                    *DAG.getContext());
3504
3505     // Allocate shadow area for Win64
3506     if (IsCalleeWin64)
3507       CCInfo.AllocateStack(32, 8);
3508
3509     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3510     if (CCInfo.getNextStackOffset()) {
3511       MachineFunction &MF = DAG.getMachineFunction();
3512       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3513         return false;
3514
3515       // Check if the arguments are already laid out in the right way as
3516       // the caller's fixed stack objects.
3517       MachineFrameInfo *MFI = MF.getFrameInfo();
3518       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3519       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3520       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3521         CCValAssign &VA = ArgLocs[i];
3522         SDValue Arg = OutVals[i];
3523         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3524         if (VA.getLocInfo() == CCValAssign::Indirect)
3525           return false;
3526         if (!VA.isRegLoc()) {
3527           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3528                                    MFI, MRI, TII))
3529             return false;
3530         }
3531       }
3532     }
3533
3534     // If the tailcall address may be in a register, then make sure it's
3535     // possible to register allocate for it. In 32-bit, the call address can
3536     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3537     // callee-saved registers are restored. These happen to be the same
3538     // registers used to pass 'inreg' arguments so watch out for those.
3539     if (!Subtarget->is64Bit() &&
3540         ((!isa<GlobalAddressSDNode>(Callee) &&
3541           !isa<ExternalSymbolSDNode>(Callee)) ||
3542          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3543       unsigned NumInRegs = 0;
3544       // In PIC we need an extra register to formulate the address computation
3545       // for the callee.
3546       unsigned MaxInRegs =
3547         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3548
3549       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3550         CCValAssign &VA = ArgLocs[i];
3551         if (!VA.isRegLoc())
3552           continue;
3553         unsigned Reg = VA.getLocReg();
3554         switch (Reg) {
3555         default: break;
3556         case X86::EAX: case X86::EDX: case X86::ECX:
3557           if (++NumInRegs == MaxInRegs)
3558             return false;
3559           break;
3560         }
3561       }
3562     }
3563   }
3564
3565   return true;
3566 }
3567
3568 FastISel *
3569 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3570                                   const TargetLibraryInfo *libInfo) const {
3571   return X86::createFastISel(funcInfo, libInfo);
3572 }
3573
3574 //===----------------------------------------------------------------------===//
3575 //                           Other Lowering Hooks
3576 //===----------------------------------------------------------------------===//
3577
3578 static bool MayFoldLoad(SDValue Op) {
3579   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3580 }
3581
3582 static bool MayFoldIntoStore(SDValue Op) {
3583   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3584 }
3585
3586 static bool isTargetShuffle(unsigned Opcode) {
3587   switch(Opcode) {
3588   default: return false;
3589   case X86ISD::BLENDI:
3590   case X86ISD::PSHUFB:
3591   case X86ISD::PSHUFD:
3592   case X86ISD::PSHUFHW:
3593   case X86ISD::PSHUFLW:
3594   case X86ISD::SHUFP:
3595   case X86ISD::PALIGNR:
3596   case X86ISD::MOVLHPS:
3597   case X86ISD::MOVLHPD:
3598   case X86ISD::MOVHLPS:
3599   case X86ISD::MOVLPS:
3600   case X86ISD::MOVLPD:
3601   case X86ISD::MOVSHDUP:
3602   case X86ISD::MOVSLDUP:
3603   case X86ISD::MOVDDUP:
3604   case X86ISD::MOVSS:
3605   case X86ISD::MOVSD:
3606   case X86ISD::UNPCKL:
3607   case X86ISD::UNPCKH:
3608   case X86ISD::VPERMILPI:
3609   case X86ISD::VPERM2X128:
3610   case X86ISD::VPERMI:
3611     return true;
3612   }
3613 }
3614
3615 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3616                                     SDValue V1, SelectionDAG &DAG) {
3617   switch(Opc) {
3618   default: llvm_unreachable("Unknown x86 shuffle node");
3619   case X86ISD::MOVSHDUP:
3620   case X86ISD::MOVSLDUP:
3621   case X86ISD::MOVDDUP:
3622     return DAG.getNode(Opc, dl, VT, V1);
3623   }
3624 }
3625
3626 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3627                                     SDValue V1, unsigned TargetMask,
3628                                     SelectionDAG &DAG) {
3629   switch(Opc) {
3630   default: llvm_unreachable("Unknown x86 shuffle node");
3631   case X86ISD::PSHUFD:
3632   case X86ISD::PSHUFHW:
3633   case X86ISD::PSHUFLW:
3634   case X86ISD::VPERMILPI:
3635   case X86ISD::VPERMI:
3636     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3637   }
3638 }
3639
3640 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3641                                     SDValue V1, SDValue V2, unsigned TargetMask,
3642                                     SelectionDAG &DAG) {
3643   switch(Opc) {
3644   default: llvm_unreachable("Unknown x86 shuffle node");
3645   case X86ISD::PALIGNR:
3646   case X86ISD::VALIGN:
3647   case X86ISD::SHUFP:
3648   case X86ISD::VPERM2X128:
3649     return DAG.getNode(Opc, dl, VT, V1, V2,
3650                        DAG.getConstant(TargetMask, MVT::i8));
3651   }
3652 }
3653
3654 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3655                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3656   switch(Opc) {
3657   default: llvm_unreachable("Unknown x86 shuffle node");
3658   case X86ISD::MOVLHPS:
3659   case X86ISD::MOVLHPD:
3660   case X86ISD::MOVHLPS:
3661   case X86ISD::MOVLPS:
3662   case X86ISD::MOVLPD:
3663   case X86ISD::MOVSS:
3664   case X86ISD::MOVSD:
3665   case X86ISD::UNPCKL:
3666   case X86ISD::UNPCKH:
3667     return DAG.getNode(Opc, dl, VT, V1, V2);
3668   }
3669 }
3670
3671 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3672   MachineFunction &MF = DAG.getMachineFunction();
3673   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3674   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3675   int ReturnAddrIndex = FuncInfo->getRAIndex();
3676
3677   if (ReturnAddrIndex == 0) {
3678     // Set up a frame object for the return address.
3679     unsigned SlotSize = RegInfo->getSlotSize();
3680     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3681                                                            -(int64_t)SlotSize,
3682                                                            false);
3683     FuncInfo->setRAIndex(ReturnAddrIndex);
3684   }
3685
3686   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3687 }
3688
3689 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3690                                        bool hasSymbolicDisplacement) {
3691   // Offset should fit into 32 bit immediate field.
3692   if (!isInt<32>(Offset))
3693     return false;
3694
3695   // If we don't have a symbolic displacement - we don't have any extra
3696   // restrictions.
3697   if (!hasSymbolicDisplacement)
3698     return true;
3699
3700   // FIXME: Some tweaks might be needed for medium code model.
3701   if (M != CodeModel::Small && M != CodeModel::Kernel)
3702     return false;
3703
3704   // For small code model we assume that latest object is 16MB before end of 31
3705   // bits boundary. We may also accept pretty large negative constants knowing
3706   // that all objects are in the positive half of address space.
3707   if (M == CodeModel::Small && Offset < 16*1024*1024)
3708     return true;
3709
3710   // For kernel code model we know that all object resist in the negative half
3711   // of 32bits address space. We may not accept negative offsets, since they may
3712   // be just off and we may accept pretty large positive ones.
3713   if (M == CodeModel::Kernel && Offset >= 0)
3714     return true;
3715
3716   return false;
3717 }
3718
3719 /// isCalleePop - Determines whether the callee is required to pop its
3720 /// own arguments. Callee pop is necessary to support tail calls.
3721 bool X86::isCalleePop(CallingConv::ID CallingConv,
3722                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3723   switch (CallingConv) {
3724   default:
3725     return false;
3726   case CallingConv::X86_StdCall:
3727   case CallingConv::X86_FastCall:
3728   case CallingConv::X86_ThisCall:
3729     return !is64Bit;
3730   case CallingConv::Fast:
3731   case CallingConv::GHC:
3732   case CallingConv::HiPE:
3733     if (IsVarArg)
3734       return false;
3735     return TailCallOpt;
3736   }
3737 }
3738
3739 /// \brief Return true if the condition is an unsigned comparison operation.
3740 static bool isX86CCUnsigned(unsigned X86CC) {
3741   switch (X86CC) {
3742   default: llvm_unreachable("Invalid integer condition!");
3743   case X86::COND_E:     return true;
3744   case X86::COND_G:     return false;
3745   case X86::COND_GE:    return false;
3746   case X86::COND_L:     return false;
3747   case X86::COND_LE:    return false;
3748   case X86::COND_NE:    return true;
3749   case X86::COND_B:     return true;
3750   case X86::COND_A:     return true;
3751   case X86::COND_BE:    return true;
3752   case X86::COND_AE:    return true;
3753   }
3754   llvm_unreachable("covered switch fell through?!");
3755 }
3756
3757 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3758 /// specific condition code, returning the condition code and the LHS/RHS of the
3759 /// comparison to make.
3760 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3761                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3762   if (!isFP) {
3763     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3764       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3765         // X > -1   -> X == 0, jump !sign.
3766         RHS = DAG.getConstant(0, RHS.getValueType());
3767         return X86::COND_NS;
3768       }
3769       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3770         // X < 0   -> X == 0, jump on sign.
3771         return X86::COND_S;
3772       }
3773       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3774         // X < 1   -> X <= 0
3775         RHS = DAG.getConstant(0, RHS.getValueType());
3776         return X86::COND_LE;
3777       }
3778     }
3779
3780     switch (SetCCOpcode) {
3781     default: llvm_unreachable("Invalid integer condition!");
3782     case ISD::SETEQ:  return X86::COND_E;
3783     case ISD::SETGT:  return X86::COND_G;
3784     case ISD::SETGE:  return X86::COND_GE;
3785     case ISD::SETLT:  return X86::COND_L;
3786     case ISD::SETLE:  return X86::COND_LE;
3787     case ISD::SETNE:  return X86::COND_NE;
3788     case ISD::SETULT: return X86::COND_B;
3789     case ISD::SETUGT: return X86::COND_A;
3790     case ISD::SETULE: return X86::COND_BE;
3791     case ISD::SETUGE: return X86::COND_AE;
3792     }
3793   }
3794
3795   // First determine if it is required or is profitable to flip the operands.
3796
3797   // If LHS is a foldable load, but RHS is not, flip the condition.
3798   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3799       !ISD::isNON_EXTLoad(RHS.getNode())) {
3800     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3801     std::swap(LHS, RHS);
3802   }
3803
3804   switch (SetCCOpcode) {
3805   default: break;
3806   case ISD::SETOLT:
3807   case ISD::SETOLE:
3808   case ISD::SETUGT:
3809   case ISD::SETUGE:
3810     std::swap(LHS, RHS);
3811     break;
3812   }
3813
3814   // On a floating point condition, the flags are set as follows:
3815   // ZF  PF  CF   op
3816   //  0 | 0 | 0 | X > Y
3817   //  0 | 0 | 1 | X < Y
3818   //  1 | 0 | 0 | X == Y
3819   //  1 | 1 | 1 | unordered
3820   switch (SetCCOpcode) {
3821   default: llvm_unreachable("Condcode should be pre-legalized away");
3822   case ISD::SETUEQ:
3823   case ISD::SETEQ:   return X86::COND_E;
3824   case ISD::SETOLT:              // flipped
3825   case ISD::SETOGT:
3826   case ISD::SETGT:   return X86::COND_A;
3827   case ISD::SETOLE:              // flipped
3828   case ISD::SETOGE:
3829   case ISD::SETGE:   return X86::COND_AE;
3830   case ISD::SETUGT:              // flipped
3831   case ISD::SETULT:
3832   case ISD::SETLT:   return X86::COND_B;
3833   case ISD::SETUGE:              // flipped
3834   case ISD::SETULE:
3835   case ISD::SETLE:   return X86::COND_BE;
3836   case ISD::SETONE:
3837   case ISD::SETNE:   return X86::COND_NE;
3838   case ISD::SETUO:   return X86::COND_P;
3839   case ISD::SETO:    return X86::COND_NP;
3840   case ISD::SETOEQ:
3841   case ISD::SETUNE:  return X86::COND_INVALID;
3842   }
3843 }
3844
3845 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3846 /// code. Current x86 isa includes the following FP cmov instructions:
3847 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3848 static bool hasFPCMov(unsigned X86CC) {
3849   switch (X86CC) {
3850   default:
3851     return false;
3852   case X86::COND_B:
3853   case X86::COND_BE:
3854   case X86::COND_E:
3855   case X86::COND_P:
3856   case X86::COND_A:
3857   case X86::COND_AE:
3858   case X86::COND_NE:
3859   case X86::COND_NP:
3860     return true;
3861   }
3862 }
3863
3864 /// isFPImmLegal - Returns true if the target can instruction select the
3865 /// specified FP immediate natively. If false, the legalizer will
3866 /// materialize the FP immediate as a load from a constant pool.
3867 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3868   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3869     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3870       return true;
3871   }
3872   return false;
3873 }
3874
3875 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3876                                               ISD::LoadExtType ExtTy,
3877                                               EVT NewVT) const {
3878   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3879   // relocation target a movq or addq instruction: don't let the load shrink.
3880   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3881   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3882     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3883       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3884   return true;
3885 }
3886
3887 /// \brief Returns true if it is beneficial to convert a load of a constant
3888 /// to just the constant itself.
3889 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3890                                                           Type *Ty) const {
3891   assert(Ty->isIntegerTy());
3892
3893   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3894   if (BitSize == 0 || BitSize > 64)
3895     return false;
3896   return true;
3897 }
3898
3899 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3900                                                 unsigned Index) const {
3901   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3902     return false;
3903
3904   return (Index == 0 || Index == ResVT.getVectorNumElements());
3905 }
3906
3907 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3908   // Speculate cttz only if we can directly use TZCNT.
3909   return Subtarget->hasBMI();
3910 }
3911
3912 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3913   // Speculate ctlz only if we can directly use LZCNT.
3914   return Subtarget->hasLZCNT();
3915 }
3916
3917 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3918 /// the specified range (L, H].
3919 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3920   return (Val < 0) || (Val >= Low && Val < Hi);
3921 }
3922
3923 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3924 /// specified value.
3925 static bool isUndefOrEqual(int Val, int CmpVal) {
3926   return (Val < 0 || Val == CmpVal);
3927 }
3928
3929 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3930 /// from position Pos and ending in Pos+Size, falls within the specified
3931 /// sequential range (Low, Low+Size]. or is undef.
3932 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3933                                        unsigned Pos, unsigned Size, int Low) {
3934   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3935     if (!isUndefOrEqual(Mask[i], Low))
3936       return false;
3937   return true;
3938 }
3939
3940 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3941 /// is suitable for input to PSHUFD. That is, it doesn't reference the other
3942 /// operand - by default will match for first operand.
3943 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT,
3944                          bool TestSecondOperand = false) {
3945   if (VT != MVT::v4f32 && VT != MVT::v4i32 &&
3946       VT != MVT::v2f64 && VT != MVT::v2i64)
3947     return false;
3948
3949   unsigned NumElems = VT.getVectorNumElements();
3950   unsigned Lo = TestSecondOperand ? NumElems : 0;
3951   unsigned Hi = Lo + NumElems;
3952
3953   for (unsigned i = 0; i < NumElems; ++i)
3954     if (!isUndefOrInRange(Mask[i], (int)Lo, (int)Hi))
3955       return false;
3956
3957   return true;
3958 }
3959
3960 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3961 /// is suitable for input to PSHUFHW.
3962 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3963   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3964     return false;
3965
3966   // Lower quadword copied in order or undef.
3967   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3968     return false;
3969
3970   // Upper quadword shuffled.
3971   for (unsigned i = 4; i != 8; ++i)
3972     if (!isUndefOrInRange(Mask[i], 4, 8))
3973       return false;
3974
3975   if (VT == MVT::v16i16) {
3976     // Lower quadword copied in order or undef.
3977     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3978       return false;
3979
3980     // Upper quadword shuffled.
3981     for (unsigned i = 12; i != 16; ++i)
3982       if (!isUndefOrInRange(Mask[i], 12, 16))
3983         return false;
3984   }
3985
3986   return true;
3987 }
3988
3989 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3990 /// is suitable for input to PSHUFLW.
3991 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3992   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3993     return false;
3994
3995   // Upper quadword copied in order.
3996   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3997     return false;
3998
3999   // Lower quadword shuffled.
4000   for (unsigned i = 0; i != 4; ++i)
4001     if (!isUndefOrInRange(Mask[i], 0, 4))
4002       return false;
4003
4004   if (VT == MVT::v16i16) {
4005     // Upper quadword copied in order.
4006     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
4007       return false;
4008
4009     // Lower quadword shuffled.
4010     for (unsigned i = 8; i != 12; ++i)
4011       if (!isUndefOrInRange(Mask[i], 8, 12))
4012         return false;
4013   }
4014
4015   return true;
4016 }
4017
4018 /// \brief Return true if the mask specifies a shuffle of elements that is
4019 /// suitable for input to intralane (palignr) or interlane (valign) vector
4020 /// right-shift.
4021 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
4022   unsigned NumElts = VT.getVectorNumElements();
4023   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
4024   unsigned NumLaneElts = NumElts/NumLanes;
4025
4026   // Do not handle 64-bit element shuffles with palignr.
4027   if (NumLaneElts == 2)
4028     return false;
4029
4030   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
4031     unsigned i;
4032     for (i = 0; i != NumLaneElts; ++i) {
4033       if (Mask[i+l] >= 0)
4034         break;
4035     }
4036
4037     // Lane is all undef, go to next lane
4038     if (i == NumLaneElts)
4039       continue;
4040
4041     int Start = Mask[i+l];
4042
4043     // Make sure its in this lane in one of the sources
4044     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
4045         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
4046       return false;
4047
4048     // If not lane 0, then we must match lane 0
4049     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
4050       return false;
4051
4052     // Correct second source to be contiguous with first source
4053     if (Start >= (int)NumElts)
4054       Start -= NumElts - NumLaneElts;
4055
4056     // Make sure we're shifting in the right direction.
4057     if (Start <= (int)(i+l))
4058       return false;
4059
4060     Start -= i;
4061
4062     // Check the rest of the elements to see if they are consecutive.
4063     for (++i; i != NumLaneElts; ++i) {
4064       int Idx = Mask[i+l];
4065
4066       // Make sure its in this lane
4067       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
4068           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
4069         return false;
4070
4071       // If not lane 0, then we must match lane 0
4072       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
4073         return false;
4074
4075       if (Idx >= (int)NumElts)
4076         Idx -= NumElts - NumLaneElts;
4077
4078       if (!isUndefOrEqual(Idx, Start+i))
4079         return false;
4080
4081     }
4082   }
4083
4084   return true;
4085 }
4086
4087 /// \brief Return true if the node specifies a shuffle of elements that is
4088 /// suitable for input to PALIGNR.
4089 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4090                           const X86Subtarget *Subtarget) {
4091   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4092       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4093       VT.is512BitVector())
4094     // FIXME: Add AVX512BW.
4095     return false;
4096
4097   return isAlignrMask(Mask, VT, false);
4098 }
4099
4100 /// \brief Return true if the node specifies a shuffle of elements that is
4101 /// suitable for input to VALIGN.
4102 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4103                           const X86Subtarget *Subtarget) {
4104   // FIXME: Add AVX512VL.
4105   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4106     return false;
4107   return isAlignrMask(Mask, VT, true);
4108 }
4109
4110 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4111 /// the two vector operands have swapped position.
4112 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4113                                      unsigned NumElems) {
4114   for (unsigned i = 0; i != NumElems; ++i) {
4115     int idx = Mask[i];
4116     if (idx < 0)
4117       continue;
4118     else if (idx < (int)NumElems)
4119       Mask[i] = idx + NumElems;
4120     else
4121       Mask[i] = idx - NumElems;
4122   }
4123 }
4124
4125 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4126 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4127 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4128 /// reverse of what x86 shuffles want.
4129 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4130
4131   unsigned NumElems = VT.getVectorNumElements();
4132   unsigned NumLanes = VT.getSizeInBits()/128;
4133   unsigned NumLaneElems = NumElems/NumLanes;
4134
4135   if (NumLaneElems != 2 && NumLaneElems != 4)
4136     return false;
4137
4138   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4139   bool symmetricMaskRequired =
4140     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4141
4142   // VSHUFPSY divides the resulting vector into 4 chunks.
4143   // The sources are also splitted into 4 chunks, and each destination
4144   // chunk must come from a different source chunk.
4145   //
4146   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4147   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4148   //
4149   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4150   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4151   //
4152   // VSHUFPDY divides the resulting vector into 4 chunks.
4153   // The sources are also splitted into 4 chunks, and each destination
4154   // chunk must come from a different source chunk.
4155   //
4156   //  SRC1 =>      X3       X2       X1       X0
4157   //  SRC2 =>      Y3       Y2       Y1       Y0
4158   //
4159   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4160   //
4161   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4162   unsigned HalfLaneElems = NumLaneElems/2;
4163   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4164     for (unsigned i = 0; i != NumLaneElems; ++i) {
4165       int Idx = Mask[i+l];
4166       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4167       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4168         return false;
4169       // For VSHUFPSY, the mask of the second half must be the same as the
4170       // first but with the appropriate offsets. This works in the same way as
4171       // VPERMILPS works with masks.
4172       if (!symmetricMaskRequired || Idx < 0)
4173         continue;
4174       if (MaskVal[i] < 0) {
4175         MaskVal[i] = Idx - l;
4176         continue;
4177       }
4178       if ((signed)(Idx - l) != MaskVal[i])
4179         return false;
4180     }
4181   }
4182
4183   return true;
4184 }
4185
4186 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4187 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4188 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4189   if (!VT.is128BitVector())
4190     return false;
4191
4192   unsigned NumElems = VT.getVectorNumElements();
4193
4194   if (NumElems != 4)
4195     return false;
4196
4197   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4198   return isUndefOrEqual(Mask[0], 6) &&
4199          isUndefOrEqual(Mask[1], 7) &&
4200          isUndefOrEqual(Mask[2], 2) &&
4201          isUndefOrEqual(Mask[3], 3);
4202 }
4203
4204 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4205 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4206 /// <2, 3, 2, 3>
4207 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4208   if (!VT.is128BitVector())
4209     return false;
4210
4211   unsigned NumElems = VT.getVectorNumElements();
4212
4213   if (NumElems != 4)
4214     return false;
4215
4216   return isUndefOrEqual(Mask[0], 2) &&
4217          isUndefOrEqual(Mask[1], 3) &&
4218          isUndefOrEqual(Mask[2], 2) &&
4219          isUndefOrEqual(Mask[3], 3);
4220 }
4221
4222 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4223 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4224 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4225   if (!VT.is128BitVector())
4226     return false;
4227
4228   unsigned NumElems = VT.getVectorNumElements();
4229
4230   if (NumElems != 2 && NumElems != 4)
4231     return false;
4232
4233   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4234     if (!isUndefOrEqual(Mask[i], i + NumElems))
4235       return false;
4236
4237   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4238     if (!isUndefOrEqual(Mask[i], i))
4239       return false;
4240
4241   return true;
4242 }
4243
4244 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4245 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4246 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4247   if (!VT.is128BitVector())
4248     return false;
4249
4250   unsigned NumElems = VT.getVectorNumElements();
4251
4252   if (NumElems != 2 && NumElems != 4)
4253     return false;
4254
4255   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4256     if (!isUndefOrEqual(Mask[i], i))
4257       return false;
4258
4259   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4260     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4261       return false;
4262
4263   return true;
4264 }
4265
4266 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4267 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4268 /// i. e: If all but one element come from the same vector.
4269 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4270   // TODO: Deal with AVX's VINSERTPS
4271   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4272     return false;
4273
4274   unsigned CorrectPosV1 = 0;
4275   unsigned CorrectPosV2 = 0;
4276   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4277     if (Mask[i] == -1) {
4278       ++CorrectPosV1;
4279       ++CorrectPosV2;
4280       continue;
4281     }
4282
4283     if (Mask[i] == i)
4284       ++CorrectPosV1;
4285     else if (Mask[i] == i + 4)
4286       ++CorrectPosV2;
4287   }
4288
4289   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4290     // We have 3 elements (undefs count as elements from any vector) from one
4291     // vector, and one from another.
4292     return true;
4293
4294   return false;
4295 }
4296
4297 //
4298 // Some special combinations that can be optimized.
4299 //
4300 static
4301 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4302                                SelectionDAG &DAG) {
4303   MVT VT = SVOp->getSimpleValueType(0);
4304   SDLoc dl(SVOp);
4305
4306   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4307     return SDValue();
4308
4309   ArrayRef<int> Mask = SVOp->getMask();
4310
4311   // These are the special masks that may be optimized.
4312   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4313   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4314   bool MatchEvenMask = true;
4315   bool MatchOddMask  = true;
4316   for (int i=0; i<8; ++i) {
4317     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4318       MatchEvenMask = false;
4319     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4320       MatchOddMask = false;
4321   }
4322
4323   if (!MatchEvenMask && !MatchOddMask)
4324     return SDValue();
4325
4326   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4327
4328   SDValue Op0 = SVOp->getOperand(0);
4329   SDValue Op1 = SVOp->getOperand(1);
4330
4331   if (MatchEvenMask) {
4332     // Shift the second operand right to 32 bits.
4333     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4334     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4335   } else {
4336     // Shift the first operand left to 32 bits.
4337     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4338     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4339   }
4340   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4341   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4342 }
4343
4344 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4345 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4346 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4347                          bool HasInt256, bool V2IsSplat = false) {
4348
4349   assert(VT.getSizeInBits() >= 128 &&
4350          "Unsupported vector type for unpckl");
4351
4352   unsigned NumElts = VT.getVectorNumElements();
4353   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4354       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4355     return false;
4356
4357   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4358          "Unsupported vector type for unpckh");
4359
4360   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4361   unsigned NumLanes = VT.getSizeInBits()/128;
4362   unsigned NumLaneElts = NumElts/NumLanes;
4363
4364   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4365     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4366       int BitI  = Mask[l+i];
4367       int BitI1 = Mask[l+i+1];
4368       if (!isUndefOrEqual(BitI, j))
4369         return false;
4370       if (V2IsSplat) {
4371         if (!isUndefOrEqual(BitI1, NumElts))
4372           return false;
4373       } else {
4374         if (!isUndefOrEqual(BitI1, j + NumElts))
4375           return false;
4376       }
4377     }
4378   }
4379
4380   return true;
4381 }
4382
4383 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4384 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4385 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4386                          bool HasInt256, bool V2IsSplat = false) {
4387   assert(VT.getSizeInBits() >= 128 &&
4388          "Unsupported vector type for unpckh");
4389
4390   unsigned NumElts = VT.getVectorNumElements();
4391   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4392       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4393     return false;
4394
4395   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4396          "Unsupported vector type for unpckh");
4397
4398   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4399   unsigned NumLanes = VT.getSizeInBits()/128;
4400   unsigned NumLaneElts = NumElts/NumLanes;
4401
4402   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4403     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4404       int BitI  = Mask[l+i];
4405       int BitI1 = Mask[l+i+1];
4406       if (!isUndefOrEqual(BitI, j))
4407         return false;
4408       if (V2IsSplat) {
4409         if (isUndefOrEqual(BitI1, NumElts))
4410           return false;
4411       } else {
4412         if (!isUndefOrEqual(BitI1, j+NumElts))
4413           return false;
4414       }
4415     }
4416   }
4417   return true;
4418 }
4419
4420 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4421 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4422 /// <0, 0, 1, 1>
4423 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4424   unsigned NumElts = VT.getVectorNumElements();
4425   bool Is256BitVec = VT.is256BitVector();
4426
4427   if (VT.is512BitVector())
4428     return false;
4429   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4430          "Unsupported vector type for unpckh");
4431
4432   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4433       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4434     return false;
4435
4436   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4437   // FIXME: Need a better way to get rid of this, there's no latency difference
4438   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4439   // the former later. We should also remove the "_undef" special mask.
4440   if (NumElts == 4 && Is256BitVec)
4441     return false;
4442
4443   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4444   // independently on 128-bit lanes.
4445   unsigned NumLanes = VT.getSizeInBits()/128;
4446   unsigned NumLaneElts = NumElts/NumLanes;
4447
4448   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4449     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4450       int BitI  = Mask[l+i];
4451       int BitI1 = Mask[l+i+1];
4452
4453       if (!isUndefOrEqual(BitI, j))
4454         return false;
4455       if (!isUndefOrEqual(BitI1, j))
4456         return false;
4457     }
4458   }
4459
4460   return true;
4461 }
4462
4463 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4464 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4465 /// <2, 2, 3, 3>
4466 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4467   unsigned NumElts = VT.getVectorNumElements();
4468
4469   if (VT.is512BitVector())
4470     return false;
4471
4472   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4473          "Unsupported vector type for unpckh");
4474
4475   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4476       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4477     return false;
4478
4479   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4480   // independently on 128-bit lanes.
4481   unsigned NumLanes = VT.getSizeInBits()/128;
4482   unsigned NumLaneElts = NumElts/NumLanes;
4483
4484   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4485     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4486       int BitI  = Mask[l+i];
4487       int BitI1 = Mask[l+i+1];
4488       if (!isUndefOrEqual(BitI, j))
4489         return false;
4490       if (!isUndefOrEqual(BitI1, j))
4491         return false;
4492     }
4493   }
4494   return true;
4495 }
4496
4497 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4498 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4499 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4500   if (!VT.is512BitVector())
4501     return false;
4502
4503   unsigned NumElts = VT.getVectorNumElements();
4504   unsigned HalfSize = NumElts/2;
4505   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4506     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4507       *Imm = 1;
4508       return true;
4509     }
4510   }
4511   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4512     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4513       *Imm = 0;
4514       return true;
4515     }
4516   }
4517   return false;
4518 }
4519
4520 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4521 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4522 /// MOVSD, and MOVD, i.e. setting the lowest element.
4523 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4524   if (VT.getVectorElementType().getSizeInBits() < 32)
4525     return false;
4526   if (!VT.is128BitVector())
4527     return false;
4528
4529   unsigned NumElts = VT.getVectorNumElements();
4530
4531   if (!isUndefOrEqual(Mask[0], NumElts))
4532     return false;
4533
4534   for (unsigned i = 1; i != NumElts; ++i)
4535     if (!isUndefOrEqual(Mask[i], i))
4536       return false;
4537
4538   return true;
4539 }
4540
4541 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4542 /// as permutations between 128-bit chunks or halves. As an example: this
4543 /// shuffle bellow:
4544 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4545 /// The first half comes from the second half of V1 and the second half from the
4546 /// the second half of V2.
4547 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4548   if (!HasFp256 || !VT.is256BitVector())
4549     return false;
4550
4551   // The shuffle result is divided into half A and half B. In total the two
4552   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4553   // B must come from C, D, E or F.
4554   unsigned HalfSize = VT.getVectorNumElements()/2;
4555   bool MatchA = false, MatchB = false;
4556
4557   // Check if A comes from one of C, D, E, F.
4558   for (unsigned Half = 0; Half != 4; ++Half) {
4559     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4560       MatchA = true;
4561       break;
4562     }
4563   }
4564
4565   // Check if B comes from one of C, D, E, F.
4566   for (unsigned Half = 0; Half != 4; ++Half) {
4567     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4568       MatchB = true;
4569       break;
4570     }
4571   }
4572
4573   return MatchA && MatchB;
4574 }
4575
4576 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4577 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4578 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4579   MVT VT = SVOp->getSimpleValueType(0);
4580
4581   unsigned HalfSize = VT.getVectorNumElements()/2;
4582
4583   unsigned FstHalf = 0, SndHalf = 0;
4584   for (unsigned i = 0; i < HalfSize; ++i) {
4585     if (SVOp->getMaskElt(i) > 0) {
4586       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4587       break;
4588     }
4589   }
4590   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4591     if (SVOp->getMaskElt(i) > 0) {
4592       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4593       break;
4594     }
4595   }
4596
4597   return (FstHalf | (SndHalf << 4));
4598 }
4599
4600 // Symmetric in-lane mask. Each lane has 4 elements (for imm8)
4601 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4602   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4603   if (EltSize < 32)
4604     return false;
4605
4606   unsigned NumElts = VT.getVectorNumElements();
4607   Imm8 = 0;
4608   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4609     for (unsigned i = 0; i != NumElts; ++i) {
4610       if (Mask[i] < 0)
4611         continue;
4612       Imm8 |= Mask[i] << (i*2);
4613     }
4614     return true;
4615   }
4616
4617   unsigned LaneSize = 4;
4618   SmallVector<int, 4> MaskVal(LaneSize, -1);
4619
4620   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4621     for (unsigned i = 0; i != LaneSize; ++i) {
4622       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4623         return false;
4624       if (Mask[i+l] < 0)
4625         continue;
4626       if (MaskVal[i] < 0) {
4627         MaskVal[i] = Mask[i+l] - l;
4628         Imm8 |= MaskVal[i] << (i*2);
4629         continue;
4630       }
4631       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4632         return false;
4633     }
4634   }
4635   return true;
4636 }
4637
4638 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4639 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4640 /// Note that VPERMIL mask matching is different depending whether theunderlying
4641 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4642 /// to the same elements of the low, but to the higher half of the source.
4643 /// In VPERMILPD the two lanes could be shuffled independently of each other
4644 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4645 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4646   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4647   if (VT.getSizeInBits() < 256 || EltSize < 32)
4648     return false;
4649   bool symmetricMaskRequired = (EltSize == 32);
4650   unsigned NumElts = VT.getVectorNumElements();
4651
4652   unsigned NumLanes = VT.getSizeInBits()/128;
4653   unsigned LaneSize = NumElts/NumLanes;
4654   // 2 or 4 elements in one lane
4655
4656   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4657   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4658     for (unsigned i = 0; i != LaneSize; ++i) {
4659       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4660         return false;
4661       if (symmetricMaskRequired) {
4662         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4663           ExpectedMaskVal[i] = Mask[i+l] - l;
4664           continue;
4665         }
4666         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4667           return false;
4668       }
4669     }
4670   }
4671   return true;
4672 }
4673
4674 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4675 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4676 /// element of vector 2 and the other elements to come from vector 1 in order.
4677 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4678                                bool V2IsSplat = false, bool V2IsUndef = false) {
4679   if (!VT.is128BitVector())
4680     return false;
4681
4682   unsigned NumOps = VT.getVectorNumElements();
4683   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4684     return false;
4685
4686   if (!isUndefOrEqual(Mask[0], 0))
4687     return false;
4688
4689   for (unsigned i = 1; i != NumOps; ++i)
4690     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4691           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4692           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4693       return false;
4694
4695   return true;
4696 }
4697
4698 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4699 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4700 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4701 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4702                            const X86Subtarget *Subtarget) {
4703   if (!Subtarget->hasSSE3())
4704     return false;
4705
4706   unsigned NumElems = VT.getVectorNumElements();
4707
4708   if ((VT.is128BitVector() && NumElems != 4) ||
4709       (VT.is256BitVector() && NumElems != 8) ||
4710       (VT.is512BitVector() && NumElems != 16))
4711     return false;
4712
4713   // "i+1" is the value the indexed mask element must have
4714   for (unsigned i = 0; i != NumElems; i += 2)
4715     if (!isUndefOrEqual(Mask[i], i+1) ||
4716         !isUndefOrEqual(Mask[i+1], i+1))
4717       return false;
4718
4719   return true;
4720 }
4721
4722 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4723 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4724 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4725 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4726                            const X86Subtarget *Subtarget) {
4727   if (!Subtarget->hasSSE3())
4728     return false;
4729
4730   unsigned NumElems = VT.getVectorNumElements();
4731
4732   if ((VT.is128BitVector() && NumElems != 4) ||
4733       (VT.is256BitVector() && NumElems != 8) ||
4734       (VT.is512BitVector() && NumElems != 16))
4735     return false;
4736
4737   // "i" is the value the indexed mask element must have
4738   for (unsigned i = 0; i != NumElems; i += 2)
4739     if (!isUndefOrEqual(Mask[i], i) ||
4740         !isUndefOrEqual(Mask[i+1], i))
4741       return false;
4742
4743   return true;
4744 }
4745
4746 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4747 /// specifies a shuffle of elements that is suitable for input to 256-bit
4748 /// version of MOVDDUP.
4749 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4750   if (!HasFp256 || !VT.is256BitVector())
4751     return false;
4752
4753   unsigned NumElts = VT.getVectorNumElements();
4754   if (NumElts != 4)
4755     return false;
4756
4757   for (unsigned i = 0; i != NumElts/2; ++i)
4758     if (!isUndefOrEqual(Mask[i], 0))
4759       return false;
4760   for (unsigned i = NumElts/2; i != NumElts; ++i)
4761     if (!isUndefOrEqual(Mask[i], NumElts/2))
4762       return false;
4763   return true;
4764 }
4765
4766 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4767 /// specifies a shuffle of elements that is suitable for input to 128-bit
4768 /// version of MOVDDUP.
4769 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4770   if (!VT.is128BitVector())
4771     return false;
4772
4773   unsigned e = VT.getVectorNumElements() / 2;
4774   for (unsigned i = 0; i != e; ++i)
4775     if (!isUndefOrEqual(Mask[i], i))
4776       return false;
4777   for (unsigned i = 0; i != e; ++i)
4778     if (!isUndefOrEqual(Mask[e+i], i))
4779       return false;
4780   return true;
4781 }
4782
4783 /// isVEXTRACTIndex - Return true if the specified
4784 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4785 /// suitable for instruction that extract 128 or 256 bit vectors
4786 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4787   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4788   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4789     return false;
4790
4791   // The index should be aligned on a vecWidth-bit boundary.
4792   uint64_t Index =
4793     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4794
4795   MVT VT = N->getSimpleValueType(0);
4796   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4797   bool Result = (Index * ElSize) % vecWidth == 0;
4798
4799   return Result;
4800 }
4801
4802 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4803 /// operand specifies a subvector insert that is suitable for input to
4804 /// insertion of 128 or 256-bit subvectors
4805 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4806   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4807   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4808     return false;
4809   // The index should be aligned on a vecWidth-bit boundary.
4810   uint64_t Index =
4811     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4812
4813   MVT VT = N->getSimpleValueType(0);
4814   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4815   bool Result = (Index * ElSize) % vecWidth == 0;
4816
4817   return Result;
4818 }
4819
4820 bool X86::isVINSERT128Index(SDNode *N) {
4821   return isVINSERTIndex(N, 128);
4822 }
4823
4824 bool X86::isVINSERT256Index(SDNode *N) {
4825   return isVINSERTIndex(N, 256);
4826 }
4827
4828 bool X86::isVEXTRACT128Index(SDNode *N) {
4829   return isVEXTRACTIndex(N, 128);
4830 }
4831
4832 bool X86::isVEXTRACT256Index(SDNode *N) {
4833   return isVEXTRACTIndex(N, 256);
4834 }
4835
4836 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4837 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4838 /// Handles 128-bit and 256-bit.
4839 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4840   MVT VT = N->getSimpleValueType(0);
4841
4842   assert((VT.getSizeInBits() >= 128) &&
4843          "Unsupported vector type for PSHUF/SHUFP");
4844
4845   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4846   // independently on 128-bit lanes.
4847   unsigned NumElts = VT.getVectorNumElements();
4848   unsigned NumLanes = VT.getSizeInBits()/128;
4849   unsigned NumLaneElts = NumElts/NumLanes;
4850
4851   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4852          "Only supports 2, 4 or 8 elements per lane");
4853
4854   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4855   unsigned Mask = 0;
4856   for (unsigned i = 0; i != NumElts; ++i) {
4857     int Elt = N->getMaskElt(i);
4858     if (Elt < 0) continue;
4859     Elt &= NumLaneElts - 1;
4860     unsigned ShAmt = (i << Shift) % 8;
4861     Mask |= Elt << ShAmt;
4862   }
4863
4864   return Mask;
4865 }
4866
4867 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4868 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4869 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4870   MVT VT = N->getSimpleValueType(0);
4871
4872   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4873          "Unsupported vector type for PSHUFHW");
4874
4875   unsigned NumElts = VT.getVectorNumElements();
4876
4877   unsigned Mask = 0;
4878   for (unsigned l = 0; l != NumElts; l += 8) {
4879     // 8 nodes per lane, but we only care about the last 4.
4880     for (unsigned i = 0; i < 4; ++i) {
4881       int Elt = N->getMaskElt(l+i+4);
4882       if (Elt < 0) continue;
4883       Elt &= 0x3; // only 2-bits.
4884       Mask |= Elt << (i * 2);
4885     }
4886   }
4887
4888   return Mask;
4889 }
4890
4891 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4892 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4893 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4894   MVT VT = N->getSimpleValueType(0);
4895
4896   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4897          "Unsupported vector type for PSHUFHW");
4898
4899   unsigned NumElts = VT.getVectorNumElements();
4900
4901   unsigned Mask = 0;
4902   for (unsigned l = 0; l != NumElts; l += 8) {
4903     // 8 nodes per lane, but we only care about the first 4.
4904     for (unsigned i = 0; i < 4; ++i) {
4905       int Elt = N->getMaskElt(l+i);
4906       if (Elt < 0) continue;
4907       Elt &= 0x3; // only 2-bits
4908       Mask |= Elt << (i * 2);
4909     }
4910   }
4911
4912   return Mask;
4913 }
4914
4915 /// \brief Return the appropriate immediate to shuffle the specified
4916 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4917 /// VALIGN (if Interlane is true) instructions.
4918 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4919                                            bool InterLane) {
4920   MVT VT = SVOp->getSimpleValueType(0);
4921   unsigned EltSize = InterLane ? 1 :
4922     VT.getVectorElementType().getSizeInBits() >> 3;
4923
4924   unsigned NumElts = VT.getVectorNumElements();
4925   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4926   unsigned NumLaneElts = NumElts/NumLanes;
4927
4928   int Val = 0;
4929   unsigned i;
4930   for (i = 0; i != NumElts; ++i) {
4931     Val = SVOp->getMaskElt(i);
4932     if (Val >= 0)
4933       break;
4934   }
4935   if (Val >= (int)NumElts)
4936     Val -= NumElts - NumLaneElts;
4937
4938   assert(Val - i > 0 && "PALIGNR imm should be positive");
4939   return (Val - i) * EltSize;
4940 }
4941
4942 /// \brief Return the appropriate immediate to shuffle the specified
4943 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4944 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4945   return getShuffleAlignrImmediate(SVOp, false);
4946 }
4947
4948 /// \brief Return the appropriate immediate to shuffle the specified
4949 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4950 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4951   return getShuffleAlignrImmediate(SVOp, true);
4952 }
4953
4954
4955 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4956   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4957   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4958     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4959
4960   uint64_t Index =
4961     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4962
4963   MVT VecVT = N->getOperand(0).getSimpleValueType();
4964   MVT ElVT = VecVT.getVectorElementType();
4965
4966   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4967   return Index / NumElemsPerChunk;
4968 }
4969
4970 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4971   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4972   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4973     llvm_unreachable("Illegal insert subvector for VINSERT");
4974
4975   uint64_t Index =
4976     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4977
4978   MVT VecVT = N->getSimpleValueType(0);
4979   MVT ElVT = VecVT.getVectorElementType();
4980
4981   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4982   return Index / NumElemsPerChunk;
4983 }
4984
4985 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4986 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4987 /// and VINSERTI128 instructions.
4988 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4989   return getExtractVEXTRACTImmediate(N, 128);
4990 }
4991
4992 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4993 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4994 /// and VINSERTI64x4 instructions.
4995 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4996   return getExtractVEXTRACTImmediate(N, 256);
4997 }
4998
4999 /// getInsertVINSERT128Immediate - Return the appropriate immediate
5000 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
5001 /// and VINSERTI128 instructions.
5002 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
5003   return getInsertVINSERTImmediate(N, 128);
5004 }
5005
5006 /// getInsertVINSERT256Immediate - Return the appropriate immediate
5007 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
5008 /// and VINSERTI64x4 instructions.
5009 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
5010   return getInsertVINSERTImmediate(N, 256);
5011 }
5012
5013 /// isZero - Returns true if Elt is a constant integer zero
5014 static bool isZero(SDValue V) {
5015   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
5016   return C && C->isNullValue();
5017 }
5018
5019 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
5020 /// constant +0.0.
5021 bool X86::isZeroNode(SDValue Elt) {
5022   if (isZero(Elt))
5023     return true;
5024   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
5025     return CFP->getValueAPF().isPosZero();
5026   return false;
5027 }
5028
5029 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
5030 /// match movhlps. The lower half elements should come from upper half of
5031 /// V1 (and in order), and the upper half elements should come from the upper
5032 /// half of V2 (and in order).
5033 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
5034   if (!VT.is128BitVector())
5035     return false;
5036   if (VT.getVectorNumElements() != 4)
5037     return false;
5038   for (unsigned i = 0, e = 2; i != e; ++i)
5039     if (!isUndefOrEqual(Mask[i], i+2))
5040       return false;
5041   for (unsigned i = 2; i != 4; ++i)
5042     if (!isUndefOrEqual(Mask[i], i+4))
5043       return false;
5044   return true;
5045 }
5046
5047 /// isScalarLoadToVector - Returns true if the node is a scalar load that
5048 /// is promoted to a vector. It also returns the LoadSDNode by reference if
5049 /// required.
5050 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
5051   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
5052     return false;
5053   N = N->getOperand(0).getNode();
5054   if (!ISD::isNON_EXTLoad(N))
5055     return false;
5056   if (LD)
5057     *LD = cast<LoadSDNode>(N);
5058   return true;
5059 }
5060
5061 // Test whether the given value is a vector value which will be legalized
5062 // into a load.
5063 static bool WillBeConstantPoolLoad(SDNode *N) {
5064   if (N->getOpcode() != ISD::BUILD_VECTOR)
5065     return false;
5066
5067   // Check for any non-constant elements.
5068   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5069     switch (N->getOperand(i).getNode()->getOpcode()) {
5070     case ISD::UNDEF:
5071     case ISD::ConstantFP:
5072     case ISD::Constant:
5073       break;
5074     default:
5075       return false;
5076     }
5077
5078   // Vectors of all-zeros and all-ones are materialized with special
5079   // instructions rather than being loaded.
5080   return !ISD::isBuildVectorAllZeros(N) &&
5081          !ISD::isBuildVectorAllOnes(N);
5082 }
5083
5084 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5085 /// match movlp{s|d}. The lower half elements should come from lower half of
5086 /// V1 (and in order), and the upper half elements should come from the upper
5087 /// half of V2 (and in order). And since V1 will become the source of the
5088 /// MOVLP, it must be either a vector load or a scalar load to vector.
5089 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5090                                ArrayRef<int> Mask, MVT VT) {
5091   if (!VT.is128BitVector())
5092     return false;
5093
5094   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5095     return false;
5096   // Is V2 is a vector load, don't do this transformation. We will try to use
5097   // load folding shufps op.
5098   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5099     return false;
5100
5101   unsigned NumElems = VT.getVectorNumElements();
5102
5103   if (NumElems != 2 && NumElems != 4)
5104     return false;
5105   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5106     if (!isUndefOrEqual(Mask[i], i))
5107       return false;
5108   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5109     if (!isUndefOrEqual(Mask[i], i+NumElems))
5110       return false;
5111   return true;
5112 }
5113
5114 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5115 /// to an zero vector.
5116 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5117 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5118   SDValue V1 = N->getOperand(0);
5119   SDValue V2 = N->getOperand(1);
5120   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5121   for (unsigned i = 0; i != NumElems; ++i) {
5122     int Idx = N->getMaskElt(i);
5123     if (Idx >= (int)NumElems) {
5124       unsigned Opc = V2.getOpcode();
5125       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5126         continue;
5127       if (Opc != ISD::BUILD_VECTOR ||
5128           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5129         return false;
5130     } else if (Idx >= 0) {
5131       unsigned Opc = V1.getOpcode();
5132       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5133         continue;
5134       if (Opc != ISD::BUILD_VECTOR ||
5135           !X86::isZeroNode(V1.getOperand(Idx)))
5136         return false;
5137     }
5138   }
5139   return true;
5140 }
5141
5142 /// getZeroVector - Returns a vector of specified type with all zero elements.
5143 ///
5144 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5145                              SelectionDAG &DAG, SDLoc dl) {
5146   assert(VT.isVector() && "Expected a vector type");
5147
5148   // Always build SSE zero vectors as <4 x i32> bitcasted
5149   // to their dest type. This ensures they get CSE'd.
5150   SDValue Vec;
5151   if (VT.is128BitVector()) {  // SSE
5152     if (Subtarget->hasSSE2()) {  // SSE2
5153       SDValue Cst = DAG.getConstant(0, MVT::i32);
5154       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5155     } else { // SSE1
5156       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5157       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5158     }
5159   } else if (VT.is256BitVector()) { // AVX
5160     if (Subtarget->hasInt256()) { // AVX2
5161       SDValue Cst = DAG.getConstant(0, MVT::i32);
5162       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5163       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5164     } else {
5165       // 256-bit logic and arithmetic instructions in AVX are all
5166       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5167       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5168       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5169       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5170     }
5171   } else if (VT.is512BitVector()) { // AVX-512
5172       SDValue Cst = DAG.getConstant(0, MVT::i32);
5173       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5174                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5175       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5176   } else if (VT.getScalarType() == MVT::i1) {
5177     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5178     SDValue Cst = DAG.getConstant(0, MVT::i1);
5179     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5180     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5181   } else
5182     llvm_unreachable("Unexpected vector type");
5183
5184   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5185 }
5186
5187 /// getOnesVector - Returns a vector of specified type with all bits set.
5188 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5189 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5190 /// Then bitcast to their original type, ensuring they get CSE'd.
5191 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5192                              SDLoc dl) {
5193   assert(VT.isVector() && "Expected a vector type");
5194
5195   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
5196   SDValue Vec;
5197   if (VT.is256BitVector()) {
5198     if (HasInt256) { // AVX2
5199       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5200       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5201     } else { // AVX
5202       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5203       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5204     }
5205   } else if (VT.is128BitVector()) {
5206     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5207   } else
5208     llvm_unreachable("Unexpected vector type");
5209
5210   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5211 }
5212
5213 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5214 /// that point to V2 points to its first element.
5215 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5216   for (unsigned i = 0; i != NumElems; ++i) {
5217     if (Mask[i] > (int)NumElems) {
5218       Mask[i] = NumElems;
5219     }
5220   }
5221 }
5222
5223 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5224 /// operation of specified width.
5225 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5226                        SDValue V2) {
5227   unsigned NumElems = VT.getVectorNumElements();
5228   SmallVector<int, 8> Mask;
5229   Mask.push_back(NumElems);
5230   for (unsigned i = 1; i != NumElems; ++i)
5231     Mask.push_back(i);
5232   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5233 }
5234
5235 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5236 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5237                           SDValue V2) {
5238   unsigned NumElems = VT.getVectorNumElements();
5239   SmallVector<int, 8> Mask;
5240   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5241     Mask.push_back(i);
5242     Mask.push_back(i + NumElems);
5243   }
5244   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5245 }
5246
5247 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5248 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5249                           SDValue V2) {
5250   unsigned NumElems = VT.getVectorNumElements();
5251   SmallVector<int, 8> Mask;
5252   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5253     Mask.push_back(i + Half);
5254     Mask.push_back(i + NumElems + Half);
5255   }
5256   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5257 }
5258
5259 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5260 // a generic shuffle instruction because the target has no such instructions.
5261 // Generate shuffles which repeat i16 and i8 several times until they can be
5262 // represented by v4f32 and then be manipulated by target suported shuffles.
5263 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5264   MVT VT = V.getSimpleValueType();
5265   int NumElems = VT.getVectorNumElements();
5266   SDLoc dl(V);
5267
5268   while (NumElems > 4) {
5269     if (EltNo < NumElems/2) {
5270       V = getUnpackl(DAG, dl, VT, V, V);
5271     } else {
5272       V = getUnpackh(DAG, dl, VT, V, V);
5273       EltNo -= NumElems/2;
5274     }
5275     NumElems >>= 1;
5276   }
5277   return V;
5278 }
5279
5280 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5281 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5282   MVT VT = V.getSimpleValueType();
5283   SDLoc dl(V);
5284
5285   if (VT.is128BitVector()) {
5286     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5287     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5288     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5289                              &SplatMask[0]);
5290   } else if (VT.is256BitVector()) {
5291     // To use VPERMILPS to splat scalars, the second half of indicies must
5292     // refer to the higher part, which is a duplication of the lower one,
5293     // because VPERMILPS can only handle in-lane permutations.
5294     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5295                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5296
5297     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5298     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5299                              &SplatMask[0]);
5300   } else
5301     llvm_unreachable("Vector size not supported");
5302
5303   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5304 }
5305
5306 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5307 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5308   MVT SrcVT = SV->getSimpleValueType(0);
5309   SDValue V1 = SV->getOperand(0);
5310   SDLoc dl(SV);
5311
5312   int EltNo = SV->getSplatIndex();
5313   int NumElems = SrcVT.getVectorNumElements();
5314   bool Is256BitVec = SrcVT.is256BitVector();
5315
5316   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5317          "Unknown how to promote splat for type");
5318
5319   // Extract the 128-bit part containing the splat element and update
5320   // the splat element index when it refers to the higher register.
5321   if (Is256BitVec) {
5322     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5323     if (EltNo >= NumElems/2)
5324       EltNo -= NumElems/2;
5325   }
5326
5327   // All i16 and i8 vector types can't be used directly by a generic shuffle
5328   // instruction because the target has no such instruction. Generate shuffles
5329   // which repeat i16 and i8 several times until they fit in i32, and then can
5330   // be manipulated by target suported shuffles.
5331   MVT EltVT = SrcVT.getVectorElementType();
5332   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5333     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5334
5335   // Recreate the 256-bit vector and place the same 128-bit vector
5336   // into the low and high part. This is necessary because we want
5337   // to use VPERM* to shuffle the vectors
5338   if (Is256BitVec) {
5339     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5340   }
5341
5342   return getLegalSplat(DAG, V1, EltNo);
5343 }
5344
5345 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5346 /// vector of zero or undef vector.  This produces a shuffle where the low
5347 /// element of V2 is swizzled into the zero/undef vector, landing at element
5348 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5349 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5350                                            bool IsZero,
5351                                            const X86Subtarget *Subtarget,
5352                                            SelectionDAG &DAG) {
5353   MVT VT = V2.getSimpleValueType();
5354   SDValue V1 = IsZero
5355     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5356   unsigned NumElems = VT.getVectorNumElements();
5357   SmallVector<int, 16> MaskVec;
5358   for (unsigned i = 0; i != NumElems; ++i)
5359     // If this is the insertion idx, put the low elt of V2 here.
5360     MaskVec.push_back(i == Idx ? NumElems : i);
5361   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5362 }
5363
5364 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5365 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5366 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5367 /// shuffles which use a single input multiple times, and in those cases it will
5368 /// adjust the mask to only have indices within that single input.
5369 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5370                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5371   unsigned NumElems = VT.getVectorNumElements();
5372   SDValue ImmN;
5373
5374   IsUnary = false;
5375   bool IsFakeUnary = false;
5376   switch(N->getOpcode()) {
5377   case X86ISD::BLENDI:
5378     ImmN = N->getOperand(N->getNumOperands()-1);
5379     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5380     break;
5381   case X86ISD::SHUFP:
5382     ImmN = N->getOperand(N->getNumOperands()-1);
5383     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5384     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5385     break;
5386   case X86ISD::UNPCKH:
5387     DecodeUNPCKHMask(VT, Mask);
5388     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5389     break;
5390   case X86ISD::UNPCKL:
5391     DecodeUNPCKLMask(VT, Mask);
5392     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5393     break;
5394   case X86ISD::MOVHLPS:
5395     DecodeMOVHLPSMask(NumElems, Mask);
5396     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5397     break;
5398   case X86ISD::MOVLHPS:
5399     DecodeMOVLHPSMask(NumElems, Mask);
5400     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5401     break;
5402   case X86ISD::PALIGNR:
5403     ImmN = N->getOperand(N->getNumOperands()-1);
5404     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5405     break;
5406   case X86ISD::PSHUFD:
5407   case X86ISD::VPERMILPI:
5408     ImmN = N->getOperand(N->getNumOperands()-1);
5409     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5410     IsUnary = true;
5411     break;
5412   case X86ISD::PSHUFHW:
5413     ImmN = N->getOperand(N->getNumOperands()-1);
5414     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5415     IsUnary = true;
5416     break;
5417   case X86ISD::PSHUFLW:
5418     ImmN = N->getOperand(N->getNumOperands()-1);
5419     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5420     IsUnary = true;
5421     break;
5422   case X86ISD::PSHUFB: {
5423     IsUnary = true;
5424     SDValue MaskNode = N->getOperand(1);
5425     while (MaskNode->getOpcode() == ISD::BITCAST)
5426       MaskNode = MaskNode->getOperand(0);
5427
5428     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5429       // If we have a build-vector, then things are easy.
5430       EVT VT = MaskNode.getValueType();
5431       assert(VT.isVector() &&
5432              "Can't produce a non-vector with a build_vector!");
5433       if (!VT.isInteger())
5434         return false;
5435
5436       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5437
5438       SmallVector<uint64_t, 32> RawMask;
5439       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5440         SDValue Op = MaskNode->getOperand(i);
5441         if (Op->getOpcode() == ISD::UNDEF) {
5442           RawMask.push_back((uint64_t)SM_SentinelUndef);
5443           continue;
5444         }
5445         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5446         if (!CN)
5447           return false;
5448         APInt MaskElement = CN->getAPIntValue();
5449
5450         // We now have to decode the element which could be any integer size and
5451         // extract each byte of it.
5452         for (int j = 0; j < NumBytesPerElement; ++j) {
5453           // Note that this is x86 and so always little endian: the low byte is
5454           // the first byte of the mask.
5455           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5456           MaskElement = MaskElement.lshr(8);
5457         }
5458       }
5459       DecodePSHUFBMask(RawMask, Mask);
5460       break;
5461     }
5462
5463     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5464     if (!MaskLoad)
5465       return false;
5466
5467     SDValue Ptr = MaskLoad->getBasePtr();
5468     if (Ptr->getOpcode() == X86ISD::Wrapper)
5469       Ptr = Ptr->getOperand(0);
5470
5471     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5472     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5473       return false;
5474
5475     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5476       DecodePSHUFBMask(C, Mask);
5477       if (Mask.empty())
5478         return false;
5479       break;
5480     }
5481
5482     return false;
5483   }
5484   case X86ISD::VPERMI:
5485     ImmN = N->getOperand(N->getNumOperands()-1);
5486     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5487     IsUnary = true;
5488     break;
5489   case X86ISD::MOVSS:
5490   case X86ISD::MOVSD:
5491     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
5492     break;
5493   case X86ISD::VPERM2X128:
5494     ImmN = N->getOperand(N->getNumOperands()-1);
5495     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5496     if (Mask.empty()) return false;
5497     break;
5498   case X86ISD::MOVSLDUP:
5499     DecodeMOVSLDUPMask(VT, Mask);
5500     IsUnary = true;
5501     break;
5502   case X86ISD::MOVSHDUP:
5503     DecodeMOVSHDUPMask(VT, Mask);
5504     IsUnary = true;
5505     break;
5506   case X86ISD::MOVDDUP:
5507     DecodeMOVDDUPMask(VT, Mask);
5508     IsUnary = true;
5509     break;
5510   case X86ISD::MOVLHPD:
5511   case X86ISD::MOVLPD:
5512   case X86ISD::MOVLPS:
5513     // Not yet implemented
5514     return false;
5515   default: llvm_unreachable("unknown target shuffle node");
5516   }
5517
5518   // If we have a fake unary shuffle, the shuffle mask is spread across two
5519   // inputs that are actually the same node. Re-map the mask to always point
5520   // into the first input.
5521   if (IsFakeUnary)
5522     for (int &M : Mask)
5523       if (M >= (int)Mask.size())
5524         M -= Mask.size();
5525
5526   return true;
5527 }
5528
5529 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5530 /// element of the result of the vector shuffle.
5531 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5532                                    unsigned Depth) {
5533   if (Depth == 6)
5534     return SDValue();  // Limit search depth.
5535
5536   SDValue V = SDValue(N, 0);
5537   EVT VT = V.getValueType();
5538   unsigned Opcode = V.getOpcode();
5539
5540   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5541   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5542     int Elt = SV->getMaskElt(Index);
5543
5544     if (Elt < 0)
5545       return DAG.getUNDEF(VT.getVectorElementType());
5546
5547     unsigned NumElems = VT.getVectorNumElements();
5548     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5549                                          : SV->getOperand(1);
5550     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5551   }
5552
5553   // Recurse into target specific vector shuffles to find scalars.
5554   if (isTargetShuffle(Opcode)) {
5555     MVT ShufVT = V.getSimpleValueType();
5556     unsigned NumElems = ShufVT.getVectorNumElements();
5557     SmallVector<int, 16> ShuffleMask;
5558     bool IsUnary;
5559
5560     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5561       return SDValue();
5562
5563     int Elt = ShuffleMask[Index];
5564     if (Elt < 0)
5565       return DAG.getUNDEF(ShufVT.getVectorElementType());
5566
5567     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5568                                          : N->getOperand(1);
5569     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5570                                Depth+1);
5571   }
5572
5573   // Actual nodes that may contain scalar elements
5574   if (Opcode == ISD::BITCAST) {
5575     V = V.getOperand(0);
5576     EVT SrcVT = V.getValueType();
5577     unsigned NumElems = VT.getVectorNumElements();
5578
5579     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5580       return SDValue();
5581   }
5582
5583   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5584     return (Index == 0) ? V.getOperand(0)
5585                         : DAG.getUNDEF(VT.getVectorElementType());
5586
5587   if (V.getOpcode() == ISD::BUILD_VECTOR)
5588     return V.getOperand(Index);
5589
5590   return SDValue();
5591 }
5592
5593 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5594 /// shuffle operation which come from a consecutively from a zero. The
5595 /// search can start in two different directions, from left or right.
5596 /// We count undefs as zeros until PreferredNum is reached.
5597 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5598                                          unsigned NumElems, bool ZerosFromLeft,
5599                                          SelectionDAG &DAG,
5600                                          unsigned PreferredNum = -1U) {
5601   unsigned NumZeros = 0;
5602   for (unsigned i = 0; i != NumElems; ++i) {
5603     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5604     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5605     if (!Elt.getNode())
5606       break;
5607
5608     if (X86::isZeroNode(Elt))
5609       ++NumZeros;
5610     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5611       NumZeros = std::min(NumZeros + 1, PreferredNum);
5612     else
5613       break;
5614   }
5615
5616   return NumZeros;
5617 }
5618
5619 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5620 /// correspond consecutively to elements from one of the vector operands,
5621 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5622 static
5623 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5624                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5625                               unsigned NumElems, unsigned &OpNum) {
5626   bool SeenV1 = false;
5627   bool SeenV2 = false;
5628
5629   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5630     int Idx = SVOp->getMaskElt(i);
5631     // Ignore undef indicies
5632     if (Idx < 0)
5633       continue;
5634
5635     if (Idx < (int)NumElems)
5636       SeenV1 = true;
5637     else
5638       SeenV2 = true;
5639
5640     // Only accept consecutive elements from the same vector
5641     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5642       return false;
5643   }
5644
5645   OpNum = SeenV1 ? 0 : 1;
5646   return true;
5647 }
5648
5649 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5650 /// logical left shift of a vector.
5651 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5652                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5653   unsigned NumElems =
5654     SVOp->getSimpleValueType(0).getVectorNumElements();
5655   unsigned NumZeros = getNumOfConsecutiveZeros(
5656       SVOp, NumElems, false /* check zeros from right */, DAG,
5657       SVOp->getMaskElt(0));
5658   unsigned OpSrc;
5659
5660   if (!NumZeros)
5661     return false;
5662
5663   // Considering the elements in the mask that are not consecutive zeros,
5664   // check if they consecutively come from only one of the source vectors.
5665   //
5666   //               V1 = {X, A, B, C}     0
5667   //                         \  \  \    /
5668   //   vector_shuffle V1, V2 <1, 2, 3, X>
5669   //
5670   if (!isShuffleMaskConsecutive(SVOp,
5671             0,                   // Mask Start Index
5672             NumElems-NumZeros,   // Mask End Index(exclusive)
5673             NumZeros,            // Where to start looking in the src vector
5674             NumElems,            // Number of elements in vector
5675             OpSrc))              // Which source operand ?
5676     return false;
5677
5678   isLeft = false;
5679   ShAmt = NumZeros;
5680   ShVal = SVOp->getOperand(OpSrc);
5681   return true;
5682 }
5683
5684 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5685 /// logical left shift of a vector.
5686 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5687                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5688   unsigned NumElems =
5689     SVOp->getSimpleValueType(0).getVectorNumElements();
5690   unsigned NumZeros = getNumOfConsecutiveZeros(
5691       SVOp, NumElems, true /* check zeros from left */, DAG,
5692       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5693   unsigned OpSrc;
5694
5695   if (!NumZeros)
5696     return false;
5697
5698   // Considering the elements in the mask that are not consecutive zeros,
5699   // check if they consecutively come from only one of the source vectors.
5700   //
5701   //                           0    { A, B, X, X } = V2
5702   //                          / \    /  /
5703   //   vector_shuffle V1, V2 <X, X, 4, 5>
5704   //
5705   if (!isShuffleMaskConsecutive(SVOp,
5706             NumZeros,     // Mask Start Index
5707             NumElems,     // Mask End Index(exclusive)
5708             0,            // Where to start looking in the src vector
5709             NumElems,     // Number of elements in vector
5710             OpSrc))       // Which source operand ?
5711     return false;
5712
5713   isLeft = true;
5714   ShAmt = NumZeros;
5715   ShVal = SVOp->getOperand(OpSrc);
5716   return true;
5717 }
5718
5719 /// isVectorShift - Returns true if the shuffle can be implemented as a
5720 /// logical left or right shift of a vector.
5721 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5722                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5723   // Although the logic below support any bitwidth size, there are no
5724   // shift instructions which handle more than 128-bit vectors.
5725   if (!SVOp->getSimpleValueType(0).is128BitVector())
5726     return false;
5727
5728   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5729       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5730     return true;
5731
5732   return false;
5733 }
5734
5735 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5736 ///
5737 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5738                                        unsigned NumNonZero, unsigned NumZero,
5739                                        SelectionDAG &DAG,
5740                                        const X86Subtarget* Subtarget,
5741                                        const TargetLowering &TLI) {
5742   if (NumNonZero > 8)
5743     return SDValue();
5744
5745   SDLoc dl(Op);
5746   SDValue V;
5747   bool First = true;
5748   for (unsigned i = 0; i < 16; ++i) {
5749     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5750     if (ThisIsNonZero && First) {
5751       if (NumZero)
5752         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5753       else
5754         V = DAG.getUNDEF(MVT::v8i16);
5755       First = false;
5756     }
5757
5758     if ((i & 1) != 0) {
5759       SDValue ThisElt, LastElt;
5760       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5761       if (LastIsNonZero) {
5762         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5763                               MVT::i16, Op.getOperand(i-1));
5764       }
5765       if (ThisIsNonZero) {
5766         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5767         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5768                               ThisElt, DAG.getConstant(8, MVT::i8));
5769         if (LastIsNonZero)
5770           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5771       } else
5772         ThisElt = LastElt;
5773
5774       if (ThisElt.getNode())
5775         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5776                         DAG.getIntPtrConstant(i/2));
5777     }
5778   }
5779
5780   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5781 }
5782
5783 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5784 ///
5785 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5786                                      unsigned NumNonZero, unsigned NumZero,
5787                                      SelectionDAG &DAG,
5788                                      const X86Subtarget* Subtarget,
5789                                      const TargetLowering &TLI) {
5790   if (NumNonZero > 4)
5791     return SDValue();
5792
5793   SDLoc dl(Op);
5794   SDValue V;
5795   bool First = true;
5796   for (unsigned i = 0; i < 8; ++i) {
5797     bool isNonZero = (NonZeros & (1 << i)) != 0;
5798     if (isNonZero) {
5799       if (First) {
5800         if (NumZero)
5801           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5802         else
5803           V = DAG.getUNDEF(MVT::v8i16);
5804         First = false;
5805       }
5806       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5807                       MVT::v8i16, V, Op.getOperand(i),
5808                       DAG.getIntPtrConstant(i));
5809     }
5810   }
5811
5812   return V;
5813 }
5814
5815 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5816 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5817                                      const X86Subtarget *Subtarget,
5818                                      const TargetLowering &TLI) {
5819   // Find all zeroable elements.
5820   bool Zeroable[4];
5821   for (int i=0; i < 4; ++i) {
5822     SDValue Elt = Op->getOperand(i);
5823     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5824   }
5825   assert(std::count_if(&Zeroable[0], &Zeroable[4],
5826                        [](bool M) { return !M; }) > 1 &&
5827          "We expect at least two non-zero elements!");
5828
5829   // We only know how to deal with build_vector nodes where elements are either
5830   // zeroable or extract_vector_elt with constant index.
5831   SDValue FirstNonZero;
5832   unsigned FirstNonZeroIdx;
5833   for (unsigned i=0; i < 4; ++i) {
5834     if (Zeroable[i])
5835       continue;
5836     SDValue Elt = Op->getOperand(i);
5837     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5838         !isa<ConstantSDNode>(Elt.getOperand(1)))
5839       return SDValue();
5840     // Make sure that this node is extracting from a 128-bit vector.
5841     MVT VT = Elt.getOperand(0).getSimpleValueType();
5842     if (!VT.is128BitVector())
5843       return SDValue();
5844     if (!FirstNonZero.getNode()) {
5845       FirstNonZero = Elt;
5846       FirstNonZeroIdx = i;
5847     }
5848   }
5849
5850   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5851   SDValue V1 = FirstNonZero.getOperand(0);
5852   MVT VT = V1.getSimpleValueType();
5853
5854   // See if this build_vector can be lowered as a blend with zero.
5855   SDValue Elt;
5856   unsigned EltMaskIdx, EltIdx;
5857   int Mask[4];
5858   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5859     if (Zeroable[EltIdx]) {
5860       // The zero vector will be on the right hand side.
5861       Mask[EltIdx] = EltIdx+4;
5862       continue;
5863     }
5864
5865     Elt = Op->getOperand(EltIdx);
5866     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5867     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5868     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5869       break;
5870     Mask[EltIdx] = EltIdx;
5871   }
5872
5873   if (EltIdx == 4) {
5874     // Let the shuffle legalizer deal with blend operations.
5875     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5876     if (V1.getSimpleValueType() != VT)
5877       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5878     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5879   }
5880
5881   // See if we can lower this build_vector to a INSERTPS.
5882   if (!Subtarget->hasSSE41())
5883     return SDValue();
5884
5885   SDValue V2 = Elt.getOperand(0);
5886   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5887     V1 = SDValue();
5888
5889   bool CanFold = true;
5890   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5891     if (Zeroable[i])
5892       continue;
5893
5894     SDValue Current = Op->getOperand(i);
5895     SDValue SrcVector = Current->getOperand(0);
5896     if (!V1.getNode())
5897       V1 = SrcVector;
5898     CanFold = SrcVector == V1 &&
5899       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5900   }
5901
5902   if (!CanFold)
5903     return SDValue();
5904
5905   assert(V1.getNode() && "Expected at least two non-zero elements!");
5906   if (V1.getSimpleValueType() != MVT::v4f32)
5907     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5908   if (V2.getSimpleValueType() != MVT::v4f32)
5909     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5910
5911   // Ok, we can emit an INSERTPS instruction.
5912   unsigned ZMask = 0;
5913   for (int i = 0; i < 4; ++i)
5914     if (Zeroable[i])
5915       ZMask |= 1 << i;
5916
5917   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5918   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5919   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
5920                                DAG.getIntPtrConstant(InsertPSMask));
5921   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
5922 }
5923
5924 /// Return a vector logical shift node.
5925 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5926                          unsigned NumBits, SelectionDAG &DAG,
5927                          const TargetLowering &TLI, SDLoc dl) {
5928   assert(VT.is128BitVector() && "Unknown type for VShift");
5929   MVT ShVT = MVT::v2i64;
5930   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5931   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5932   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
5933   SDValue ShiftVal = DAG.getConstant(NumBits, ScalarShiftTy);
5934   return DAG.getNode(ISD::BITCAST, dl, VT,
5935                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5936 }
5937
5938 static SDValue
5939 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5940
5941   // Check if the scalar load can be widened into a vector load. And if
5942   // the address is "base + cst" see if the cst can be "absorbed" into
5943   // the shuffle mask.
5944   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5945     SDValue Ptr = LD->getBasePtr();
5946     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5947       return SDValue();
5948     EVT PVT = LD->getValueType(0);
5949     if (PVT != MVT::i32 && PVT != MVT::f32)
5950       return SDValue();
5951
5952     int FI = -1;
5953     int64_t Offset = 0;
5954     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5955       FI = FINode->getIndex();
5956       Offset = 0;
5957     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5958                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5959       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5960       Offset = Ptr.getConstantOperandVal(1);
5961       Ptr = Ptr.getOperand(0);
5962     } else {
5963       return SDValue();
5964     }
5965
5966     // FIXME: 256-bit vector instructions don't require a strict alignment,
5967     // improve this code to support it better.
5968     unsigned RequiredAlign = VT.getSizeInBits()/8;
5969     SDValue Chain = LD->getChain();
5970     // Make sure the stack object alignment is at least 16 or 32.
5971     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5972     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5973       if (MFI->isFixedObjectIndex(FI)) {
5974         // Can't change the alignment. FIXME: It's possible to compute
5975         // the exact stack offset and reference FI + adjust offset instead.
5976         // If someone *really* cares about this. That's the way to implement it.
5977         return SDValue();
5978       } else {
5979         MFI->setObjectAlignment(FI, RequiredAlign);
5980       }
5981     }
5982
5983     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5984     // Ptr + (Offset & ~15).
5985     if (Offset < 0)
5986       return SDValue();
5987     if ((Offset % RequiredAlign) & 3)
5988       return SDValue();
5989     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5990     if (StartOffset)
5991       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5992                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5993
5994     int EltNo = (Offset - StartOffset) >> 2;
5995     unsigned NumElems = VT.getVectorNumElements();
5996
5997     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5998     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5999                              LD->getPointerInfo().getWithOffset(StartOffset),
6000                              false, false, false, 0);
6001
6002     SmallVector<int, 8> Mask;
6003     for (unsigned i = 0; i != NumElems; ++i)
6004       Mask.push_back(EltNo);
6005
6006     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
6007   }
6008
6009   return SDValue();
6010 }
6011
6012 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
6013 /// elements can be replaced by a single large load which has the same value as
6014 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
6015 ///
6016 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
6017 ///
6018 /// FIXME: we'd also like to handle the case where the last elements are zero
6019 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
6020 /// There's even a handy isZeroNode for that purpose.
6021 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
6022                                         SDLoc &DL, SelectionDAG &DAG,
6023                                         bool isAfterLegalize) {
6024   unsigned NumElems = Elts.size();
6025
6026   LoadSDNode *LDBase = nullptr;
6027   unsigned LastLoadedElt = -1U;
6028
6029   // For each element in the initializer, see if we've found a load or an undef.
6030   // If we don't find an initial load element, or later load elements are
6031   // non-consecutive, bail out.
6032   for (unsigned i = 0; i < NumElems; ++i) {
6033     SDValue Elt = Elts[i];
6034     // Look through a bitcast.
6035     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
6036       Elt = Elt.getOperand(0);
6037     if (!Elt.getNode() ||
6038         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
6039       return SDValue();
6040     if (!LDBase) {
6041       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
6042         return SDValue();
6043       LDBase = cast<LoadSDNode>(Elt.getNode());
6044       LastLoadedElt = i;
6045       continue;
6046     }
6047     if (Elt.getOpcode() == ISD::UNDEF)
6048       continue;
6049
6050     LoadSDNode *LD = cast<LoadSDNode>(Elt);
6051     EVT LdVT = Elt.getValueType();
6052     // Each loaded element must be the correct fractional portion of the
6053     // requested vector load.
6054     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
6055       return SDValue();
6056     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
6057       return SDValue();
6058     LastLoadedElt = i;
6059   }
6060
6061   // If we have found an entire vector of loads and undefs, then return a large
6062   // load of the entire vector width starting at the base pointer.  If we found
6063   // consecutive loads for the low half, generate a vzext_load node.
6064   if (LastLoadedElt == NumElems - 1) {
6065     assert(LDBase && "Did not find base load for merging consecutive loads");
6066     EVT EltVT = LDBase->getValueType(0);
6067     // Ensure that the input vector size for the merged loads matches the
6068     // cumulative size of the input elements.
6069     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
6070       return SDValue();
6071
6072     if (isAfterLegalize &&
6073         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
6074       return SDValue();
6075
6076     SDValue NewLd = SDValue();
6077
6078     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6079                         LDBase->getPointerInfo(), LDBase->isVolatile(),
6080                         LDBase->isNonTemporal(), LDBase->isInvariant(),
6081                         LDBase->getAlignment());
6082
6083     if (LDBase->hasAnyUseOfValue(1)) {
6084       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6085                                      SDValue(LDBase, 1),
6086                                      SDValue(NewLd.getNode(), 1));
6087       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6088       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6089                              SDValue(NewLd.getNode(), 1));
6090     }
6091
6092     return NewLd;
6093   }
6094
6095   //TODO: The code below fires only for for loading the low v2i32 / v2f32
6096   //of a v4i32 / v4f32. It's probably worth generalizing.
6097   EVT EltVT = VT.getVectorElementType();
6098   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
6099       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
6100     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
6101     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
6102     SDValue ResNode =
6103         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
6104                                 LDBase->getPointerInfo(),
6105                                 LDBase->getAlignment(),
6106                                 false/*isVolatile*/, true/*ReadMem*/,
6107                                 false/*WriteMem*/);
6108
6109     // Make sure the newly-created LOAD is in the same position as LDBase in
6110     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
6111     // update uses of LDBase's output chain to use the TokenFactor.
6112     if (LDBase->hasAnyUseOfValue(1)) {
6113       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6114                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
6115       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6116       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6117                              SDValue(ResNode.getNode(), 1));
6118     }
6119
6120     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
6121   }
6122   return SDValue();
6123 }
6124
6125 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6126 /// to generate a splat value for the following cases:
6127 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6128 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6129 /// a scalar load, or a constant.
6130 /// The VBROADCAST node is returned when a pattern is found,
6131 /// or SDValue() otherwise.
6132 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6133                                     SelectionDAG &DAG) {
6134   // VBROADCAST requires AVX.
6135   // TODO: Splats could be generated for non-AVX CPUs using SSE
6136   // instructions, but there's less potential gain for only 128-bit vectors.
6137   if (!Subtarget->hasAVX())
6138     return SDValue();
6139
6140   MVT VT = Op.getSimpleValueType();
6141   SDLoc dl(Op);
6142
6143   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6144          "Unsupported vector type for broadcast.");
6145
6146   SDValue Ld;
6147   bool ConstSplatVal;
6148
6149   switch (Op.getOpcode()) {
6150     default:
6151       // Unknown pattern found.
6152       return SDValue();
6153
6154     case ISD::BUILD_VECTOR: {
6155       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6156       BitVector UndefElements;
6157       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6158
6159       // We need a splat of a single value to use broadcast, and it doesn't
6160       // make any sense if the value is only in one element of the vector.
6161       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6162         return SDValue();
6163
6164       Ld = Splat;
6165       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6166                        Ld.getOpcode() == ISD::ConstantFP);
6167
6168       // Make sure that all of the users of a non-constant load are from the
6169       // BUILD_VECTOR node.
6170       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6171         return SDValue();
6172       break;
6173     }
6174
6175     case ISD::VECTOR_SHUFFLE: {
6176       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6177
6178       // Shuffles must have a splat mask where the first element is
6179       // broadcasted.
6180       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6181         return SDValue();
6182
6183       SDValue Sc = Op.getOperand(0);
6184       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6185           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6186
6187         if (!Subtarget->hasInt256())
6188           return SDValue();
6189
6190         // Use the register form of the broadcast instruction available on AVX2.
6191         if (VT.getSizeInBits() >= 256)
6192           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6193         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6194       }
6195
6196       Ld = Sc.getOperand(0);
6197       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6198                        Ld.getOpcode() == ISD::ConstantFP);
6199
6200       // The scalar_to_vector node and the suspected
6201       // load node must have exactly one user.
6202       // Constants may have multiple users.
6203
6204       // AVX-512 has register version of the broadcast
6205       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6206         Ld.getValueType().getSizeInBits() >= 32;
6207       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6208           !hasRegVer))
6209         return SDValue();
6210       break;
6211     }
6212   }
6213
6214   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6215   bool IsGE256 = (VT.getSizeInBits() >= 256);
6216
6217   // When optimizing for size, generate up to 5 extra bytes for a broadcast
6218   // instruction to save 8 or more bytes of constant pool data.
6219   // TODO: If multiple splats are generated to load the same constant,
6220   // it may be detrimental to overall size. There needs to be a way to detect
6221   // that condition to know if this is truly a size win.
6222   const Function *F = DAG.getMachineFunction().getFunction();
6223   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
6224
6225   // Handle broadcasting a single constant scalar from the constant pool
6226   // into a vector.
6227   // On Sandybridge (no AVX2), it is still better to load a constant vector
6228   // from the constant pool and not to broadcast it from a scalar.
6229   // But override that restriction when optimizing for size.
6230   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6231   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
6232     EVT CVT = Ld.getValueType();
6233     assert(!CVT.isVector() && "Must not broadcast a vector type");
6234
6235     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6236     // For size optimization, also splat v2f64 and v2i64, and for size opt
6237     // with AVX2, also splat i8 and i16.
6238     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6239     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6240         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
6241       const Constant *C = nullptr;
6242       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6243         C = CI->getConstantIntValue();
6244       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6245         C = CF->getConstantFPValue();
6246
6247       assert(C && "Invalid constant type");
6248
6249       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6250       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6251       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6252       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6253                        MachinePointerInfo::getConstantPool(),
6254                        false, false, false, Alignment);
6255
6256       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6257     }
6258   }
6259
6260   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6261
6262   // Handle AVX2 in-register broadcasts.
6263   if (!IsLoad && Subtarget->hasInt256() &&
6264       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6265     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6266
6267   // The scalar source must be a normal load.
6268   if (!IsLoad)
6269     return SDValue();
6270
6271   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6272       (Subtarget->hasVLX() && ScalarSize == 64))
6273     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6274
6275   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6276   // double since there is no vbroadcastsd xmm
6277   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6278     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6279       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6280   }
6281
6282   // Unsupported broadcast.
6283   return SDValue();
6284 }
6285
6286 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6287 /// underlying vector and index.
6288 ///
6289 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6290 /// index.
6291 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6292                                          SDValue ExtIdx) {
6293   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6294   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6295     return Idx;
6296
6297   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6298   // lowered this:
6299   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6300   // to:
6301   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6302   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6303   //                           undef)
6304   //                       Constant<0>)
6305   // In this case the vector is the extract_subvector expression and the index
6306   // is 2, as specified by the shuffle.
6307   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6308   SDValue ShuffleVec = SVOp->getOperand(0);
6309   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6310   assert(ShuffleVecVT.getVectorElementType() ==
6311          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6312
6313   int ShuffleIdx = SVOp->getMaskElt(Idx);
6314   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6315     ExtractedFromVec = ShuffleVec;
6316     return ShuffleIdx;
6317   }
6318   return Idx;
6319 }
6320
6321 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6322   MVT VT = Op.getSimpleValueType();
6323
6324   // Skip if insert_vec_elt is not supported.
6325   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6326   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6327     return SDValue();
6328
6329   SDLoc DL(Op);
6330   unsigned NumElems = Op.getNumOperands();
6331
6332   SDValue VecIn1;
6333   SDValue VecIn2;
6334   SmallVector<unsigned, 4> InsertIndices;
6335   SmallVector<int, 8> Mask(NumElems, -1);
6336
6337   for (unsigned i = 0; i != NumElems; ++i) {
6338     unsigned Opc = Op.getOperand(i).getOpcode();
6339
6340     if (Opc == ISD::UNDEF)
6341       continue;
6342
6343     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6344       // Quit if more than 1 elements need inserting.
6345       if (InsertIndices.size() > 1)
6346         return SDValue();
6347
6348       InsertIndices.push_back(i);
6349       continue;
6350     }
6351
6352     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6353     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6354     // Quit if non-constant index.
6355     if (!isa<ConstantSDNode>(ExtIdx))
6356       return SDValue();
6357     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6358
6359     // Quit if extracted from vector of different type.
6360     if (ExtractedFromVec.getValueType() != VT)
6361       return SDValue();
6362
6363     if (!VecIn1.getNode())
6364       VecIn1 = ExtractedFromVec;
6365     else if (VecIn1 != ExtractedFromVec) {
6366       if (!VecIn2.getNode())
6367         VecIn2 = ExtractedFromVec;
6368       else if (VecIn2 != ExtractedFromVec)
6369         // Quit if more than 2 vectors to shuffle
6370         return SDValue();
6371     }
6372
6373     if (ExtractedFromVec == VecIn1)
6374       Mask[i] = Idx;
6375     else if (ExtractedFromVec == VecIn2)
6376       Mask[i] = Idx + NumElems;
6377   }
6378
6379   if (!VecIn1.getNode())
6380     return SDValue();
6381
6382   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6383   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6384   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6385     unsigned Idx = InsertIndices[i];
6386     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6387                      DAG.getIntPtrConstant(Idx));
6388   }
6389
6390   return NV;
6391 }
6392
6393 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6394 SDValue
6395 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6396
6397   MVT VT = Op.getSimpleValueType();
6398   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6399          "Unexpected type in LowerBUILD_VECTORvXi1!");
6400
6401   SDLoc dl(Op);
6402   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6403     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6404     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6405     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6406   }
6407
6408   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6409     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6410     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6411     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6412   }
6413
6414   bool AllContants = true;
6415   uint64_t Immediate = 0;
6416   int NonConstIdx = -1;
6417   bool IsSplat = true;
6418   unsigned NumNonConsts = 0;
6419   unsigned NumConsts = 0;
6420   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6421     SDValue In = Op.getOperand(idx);
6422     if (In.getOpcode() == ISD::UNDEF)
6423       continue;
6424     if (!isa<ConstantSDNode>(In)) {
6425       AllContants = false;
6426       NonConstIdx = idx;
6427       NumNonConsts++;
6428     } else {
6429       NumConsts++;
6430       if (cast<ConstantSDNode>(In)->getZExtValue())
6431       Immediate |= (1ULL << idx);
6432     }
6433     if (In != Op.getOperand(0))
6434       IsSplat = false;
6435   }
6436
6437   if (AllContants) {
6438     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6439       DAG.getConstant(Immediate, MVT::i16));
6440     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6441                        DAG.getIntPtrConstant(0));
6442   }
6443
6444   if (NumNonConsts == 1 && NonConstIdx != 0) {
6445     SDValue DstVec;
6446     if (NumConsts) {
6447       SDValue VecAsImm = DAG.getConstant(Immediate,
6448                                          MVT::getIntegerVT(VT.getSizeInBits()));
6449       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6450     }
6451     else
6452       DstVec = DAG.getUNDEF(VT);
6453     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6454                        Op.getOperand(NonConstIdx),
6455                        DAG.getIntPtrConstant(NonConstIdx));
6456   }
6457   if (!IsSplat && (NonConstIdx != 0))
6458     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6459   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6460   SDValue Select;
6461   if (IsSplat)
6462     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6463                           DAG.getConstant(-1, SelectVT),
6464                           DAG.getConstant(0, SelectVT));
6465   else
6466     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6467                          DAG.getConstant((Immediate | 1), SelectVT),
6468                          DAG.getConstant(Immediate, SelectVT));
6469   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6470 }
6471
6472 /// \brief Return true if \p N implements a horizontal binop and return the
6473 /// operands for the horizontal binop into V0 and V1.
6474 ///
6475 /// This is a helper function of PerformBUILD_VECTORCombine.
6476 /// This function checks that the build_vector \p N in input implements a
6477 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6478 /// operation to match.
6479 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6480 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6481 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6482 /// arithmetic sub.
6483 ///
6484 /// This function only analyzes elements of \p N whose indices are
6485 /// in range [BaseIdx, LastIdx).
6486 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6487                               SelectionDAG &DAG,
6488                               unsigned BaseIdx, unsigned LastIdx,
6489                               SDValue &V0, SDValue &V1) {
6490   EVT VT = N->getValueType(0);
6491
6492   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6493   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6494          "Invalid Vector in input!");
6495
6496   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6497   bool CanFold = true;
6498   unsigned ExpectedVExtractIdx = BaseIdx;
6499   unsigned NumElts = LastIdx - BaseIdx;
6500   V0 = DAG.getUNDEF(VT);
6501   V1 = DAG.getUNDEF(VT);
6502
6503   // Check if N implements a horizontal binop.
6504   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6505     SDValue Op = N->getOperand(i + BaseIdx);
6506
6507     // Skip UNDEFs.
6508     if (Op->getOpcode() == ISD::UNDEF) {
6509       // Update the expected vector extract index.
6510       if (i * 2 == NumElts)
6511         ExpectedVExtractIdx = BaseIdx;
6512       ExpectedVExtractIdx += 2;
6513       continue;
6514     }
6515
6516     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6517
6518     if (!CanFold)
6519       break;
6520
6521     SDValue Op0 = Op.getOperand(0);
6522     SDValue Op1 = Op.getOperand(1);
6523
6524     // Try to match the following pattern:
6525     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6526     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6527         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6528         Op0.getOperand(0) == Op1.getOperand(0) &&
6529         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6530         isa<ConstantSDNode>(Op1.getOperand(1)));
6531     if (!CanFold)
6532       break;
6533
6534     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6535     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6536
6537     if (i * 2 < NumElts) {
6538       if (V0.getOpcode() == ISD::UNDEF)
6539         V0 = Op0.getOperand(0);
6540     } else {
6541       if (V1.getOpcode() == ISD::UNDEF)
6542         V1 = Op0.getOperand(0);
6543       if (i * 2 == NumElts)
6544         ExpectedVExtractIdx = BaseIdx;
6545     }
6546
6547     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6548     if (I0 == ExpectedVExtractIdx)
6549       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6550     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6551       // Try to match the following dag sequence:
6552       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6553       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6554     } else
6555       CanFold = false;
6556
6557     ExpectedVExtractIdx += 2;
6558   }
6559
6560   return CanFold;
6561 }
6562
6563 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6564 /// a concat_vector.
6565 ///
6566 /// This is a helper function of PerformBUILD_VECTORCombine.
6567 /// This function expects two 256-bit vectors called V0 and V1.
6568 /// At first, each vector is split into two separate 128-bit vectors.
6569 /// Then, the resulting 128-bit vectors are used to implement two
6570 /// horizontal binary operations.
6571 ///
6572 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6573 ///
6574 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6575 /// the two new horizontal binop.
6576 /// When Mode is set, the first horizontal binop dag node would take as input
6577 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6578 /// horizontal binop dag node would take as input the lower 128-bit of V1
6579 /// and the upper 128-bit of V1.
6580 ///   Example:
6581 ///     HADD V0_LO, V0_HI
6582 ///     HADD V1_LO, V1_HI
6583 ///
6584 /// Otherwise, the first horizontal binop dag node takes as input the lower
6585 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6586 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6587 ///   Example:
6588 ///     HADD V0_LO, V1_LO
6589 ///     HADD V0_HI, V1_HI
6590 ///
6591 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6592 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6593 /// the upper 128-bits of the result.
6594 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6595                                      SDLoc DL, SelectionDAG &DAG,
6596                                      unsigned X86Opcode, bool Mode,
6597                                      bool isUndefLO, bool isUndefHI) {
6598   EVT VT = V0.getValueType();
6599   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6600          "Invalid nodes in input!");
6601
6602   unsigned NumElts = VT.getVectorNumElements();
6603   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6604   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6605   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6606   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6607   EVT NewVT = V0_LO.getValueType();
6608
6609   SDValue LO = DAG.getUNDEF(NewVT);
6610   SDValue HI = DAG.getUNDEF(NewVT);
6611
6612   if (Mode) {
6613     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6614     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6615       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6616     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6617       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6618   } else {
6619     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6620     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6621                        V1_LO->getOpcode() != ISD::UNDEF))
6622       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6623
6624     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6625                        V1_HI->getOpcode() != ISD::UNDEF))
6626       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6627   }
6628
6629   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6630 }
6631
6632 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6633 /// sequence of 'vadd + vsub + blendi'.
6634 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6635                            const X86Subtarget *Subtarget) {
6636   SDLoc DL(BV);
6637   EVT VT = BV->getValueType(0);
6638   unsigned NumElts = VT.getVectorNumElements();
6639   SDValue InVec0 = DAG.getUNDEF(VT);
6640   SDValue InVec1 = DAG.getUNDEF(VT);
6641
6642   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6643           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6644
6645   // Odd-numbered elements in the input build vector are obtained from
6646   // adding two integer/float elements.
6647   // Even-numbered elements in the input build vector are obtained from
6648   // subtracting two integer/float elements.
6649   unsigned ExpectedOpcode = ISD::FSUB;
6650   unsigned NextExpectedOpcode = ISD::FADD;
6651   bool AddFound = false;
6652   bool SubFound = false;
6653
6654   for (unsigned i = 0, e = NumElts; i != e; i++) {
6655     SDValue Op = BV->getOperand(i);
6656
6657     // Skip 'undef' values.
6658     unsigned Opcode = Op.getOpcode();
6659     if (Opcode == ISD::UNDEF) {
6660       std::swap(ExpectedOpcode, NextExpectedOpcode);
6661       continue;
6662     }
6663
6664     // Early exit if we found an unexpected opcode.
6665     if (Opcode != ExpectedOpcode)
6666       return SDValue();
6667
6668     SDValue Op0 = Op.getOperand(0);
6669     SDValue Op1 = Op.getOperand(1);
6670
6671     // Try to match the following pattern:
6672     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6673     // Early exit if we cannot match that sequence.
6674     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6675         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6676         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6677         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6678         Op0.getOperand(1) != Op1.getOperand(1))
6679       return SDValue();
6680
6681     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6682     if (I0 != i)
6683       return SDValue();
6684
6685     // We found a valid add/sub node. Update the information accordingly.
6686     if (i & 1)
6687       AddFound = true;
6688     else
6689       SubFound = true;
6690
6691     // Update InVec0 and InVec1.
6692     if (InVec0.getOpcode() == ISD::UNDEF)
6693       InVec0 = Op0.getOperand(0);
6694     if (InVec1.getOpcode() == ISD::UNDEF)
6695       InVec1 = Op1.getOperand(0);
6696
6697     // Make sure that operands in input to each add/sub node always
6698     // come from a same pair of vectors.
6699     if (InVec0 != Op0.getOperand(0)) {
6700       if (ExpectedOpcode == ISD::FSUB)
6701         return SDValue();
6702
6703       // FADD is commutable. Try to commute the operands
6704       // and then test again.
6705       std::swap(Op0, Op1);
6706       if (InVec0 != Op0.getOperand(0))
6707         return SDValue();
6708     }
6709
6710     if (InVec1 != Op1.getOperand(0))
6711       return SDValue();
6712
6713     // Update the pair of expected opcodes.
6714     std::swap(ExpectedOpcode, NextExpectedOpcode);
6715   }
6716
6717   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6718   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6719       InVec1.getOpcode() != ISD::UNDEF)
6720     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6721
6722   return SDValue();
6723 }
6724
6725 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6726                                           const X86Subtarget *Subtarget) {
6727   SDLoc DL(N);
6728   EVT VT = N->getValueType(0);
6729   unsigned NumElts = VT.getVectorNumElements();
6730   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6731   SDValue InVec0, InVec1;
6732
6733   // Try to match an ADDSUB.
6734   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6735       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6736     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6737     if (Value.getNode())
6738       return Value;
6739   }
6740
6741   // Try to match horizontal ADD/SUB.
6742   unsigned NumUndefsLO = 0;
6743   unsigned NumUndefsHI = 0;
6744   unsigned Half = NumElts/2;
6745
6746   // Count the number of UNDEF operands in the build_vector in input.
6747   for (unsigned i = 0, e = Half; i != e; ++i)
6748     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6749       NumUndefsLO++;
6750
6751   for (unsigned i = Half, e = NumElts; i != e; ++i)
6752     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6753       NumUndefsHI++;
6754
6755   // Early exit if this is either a build_vector of all UNDEFs or all the
6756   // operands but one are UNDEF.
6757   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6758     return SDValue();
6759
6760   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6761     // Try to match an SSE3 float HADD/HSUB.
6762     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6763       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6764
6765     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6766       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6767   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6768     // Try to match an SSSE3 integer HADD/HSUB.
6769     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6770       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6771
6772     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6773       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6774   }
6775
6776   if (!Subtarget->hasAVX())
6777     return SDValue();
6778
6779   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6780     // Try to match an AVX horizontal add/sub of packed single/double
6781     // precision floating point values from 256-bit vectors.
6782     SDValue InVec2, InVec3;
6783     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6784         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6785         ((InVec0.getOpcode() == ISD::UNDEF ||
6786           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6787         ((InVec1.getOpcode() == ISD::UNDEF ||
6788           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6789       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6790
6791     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6792         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6793         ((InVec0.getOpcode() == ISD::UNDEF ||
6794           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6795         ((InVec1.getOpcode() == ISD::UNDEF ||
6796           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6797       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6798   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6799     // Try to match an AVX2 horizontal add/sub of signed integers.
6800     SDValue InVec2, InVec3;
6801     unsigned X86Opcode;
6802     bool CanFold = true;
6803
6804     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6805         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6806         ((InVec0.getOpcode() == ISD::UNDEF ||
6807           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6808         ((InVec1.getOpcode() == ISD::UNDEF ||
6809           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6810       X86Opcode = X86ISD::HADD;
6811     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6812         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6813         ((InVec0.getOpcode() == ISD::UNDEF ||
6814           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6815         ((InVec1.getOpcode() == ISD::UNDEF ||
6816           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6817       X86Opcode = X86ISD::HSUB;
6818     else
6819       CanFold = false;
6820
6821     if (CanFold) {
6822       // Fold this build_vector into a single horizontal add/sub.
6823       // Do this only if the target has AVX2.
6824       if (Subtarget->hasAVX2())
6825         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6826
6827       // Do not try to expand this build_vector into a pair of horizontal
6828       // add/sub if we can emit a pair of scalar add/sub.
6829       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6830         return SDValue();
6831
6832       // Convert this build_vector into a pair of horizontal binop followed by
6833       // a concat vector.
6834       bool isUndefLO = NumUndefsLO == Half;
6835       bool isUndefHI = NumUndefsHI == Half;
6836       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6837                                    isUndefLO, isUndefHI);
6838     }
6839   }
6840
6841   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6842        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6843     unsigned X86Opcode;
6844     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6845       X86Opcode = X86ISD::HADD;
6846     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6847       X86Opcode = X86ISD::HSUB;
6848     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6849       X86Opcode = X86ISD::FHADD;
6850     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6851       X86Opcode = X86ISD::FHSUB;
6852     else
6853       return SDValue();
6854
6855     // Don't try to expand this build_vector into a pair of horizontal add/sub
6856     // if we can simply emit a pair of scalar add/sub.
6857     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6858       return SDValue();
6859
6860     // Convert this build_vector into two horizontal add/sub followed by
6861     // a concat vector.
6862     bool isUndefLO = NumUndefsLO == Half;
6863     bool isUndefHI = NumUndefsHI == Half;
6864     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6865                                  isUndefLO, isUndefHI);
6866   }
6867
6868   return SDValue();
6869 }
6870
6871 SDValue
6872 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6873   SDLoc dl(Op);
6874
6875   MVT VT = Op.getSimpleValueType();
6876   MVT ExtVT = VT.getVectorElementType();
6877   unsigned NumElems = Op.getNumOperands();
6878
6879   // Generate vectors for predicate vectors.
6880   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6881     return LowerBUILD_VECTORvXi1(Op, DAG);
6882
6883   // Vectors containing all zeros can be matched by pxor and xorps later
6884   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6885     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6886     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6887     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6888       return Op;
6889
6890     return getZeroVector(VT, Subtarget, DAG, dl);
6891   }
6892
6893   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6894   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6895   // vpcmpeqd on 256-bit vectors.
6896   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6897     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6898       return Op;
6899
6900     if (!VT.is512BitVector())
6901       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6902   }
6903
6904   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6905   if (Broadcast.getNode())
6906     return Broadcast;
6907
6908   unsigned EVTBits = ExtVT.getSizeInBits();
6909
6910   unsigned NumZero  = 0;
6911   unsigned NumNonZero = 0;
6912   unsigned NonZeros = 0;
6913   bool IsAllConstants = true;
6914   SmallSet<SDValue, 8> Values;
6915   for (unsigned i = 0; i < NumElems; ++i) {
6916     SDValue Elt = Op.getOperand(i);
6917     if (Elt.getOpcode() == ISD::UNDEF)
6918       continue;
6919     Values.insert(Elt);
6920     if (Elt.getOpcode() != ISD::Constant &&
6921         Elt.getOpcode() != ISD::ConstantFP)
6922       IsAllConstants = false;
6923     if (X86::isZeroNode(Elt))
6924       NumZero++;
6925     else {
6926       NonZeros |= (1 << i);
6927       NumNonZero++;
6928     }
6929   }
6930
6931   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6932   if (NumNonZero == 0)
6933     return DAG.getUNDEF(VT);
6934
6935   // Special case for single non-zero, non-undef, element.
6936   if (NumNonZero == 1) {
6937     unsigned Idx = countTrailingZeros(NonZeros);
6938     SDValue Item = Op.getOperand(Idx);
6939
6940     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6941     // the value are obviously zero, truncate the value to i32 and do the
6942     // insertion that way.  Only do this if the value is non-constant or if the
6943     // value is a constant being inserted into element 0.  It is cheaper to do
6944     // a constant pool load than it is to do a movd + shuffle.
6945     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6946         (!IsAllConstants || Idx == 0)) {
6947       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6948         // Handle SSE only.
6949         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6950         EVT VecVT = MVT::v4i32;
6951         unsigned VecElts = 4;
6952
6953         // Truncate the value (which may itself be a constant) to i32, and
6954         // convert it to a vector with movd (S2V+shuffle to zero extend).
6955         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6956         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6957
6958         // If using the new shuffle lowering, just directly insert this.
6959         if (ExperimentalVectorShuffleLowering)
6960           return DAG.getNode(
6961               ISD::BITCAST, dl, VT,
6962               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6963
6964         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6965
6966         // Now we have our 32-bit value zero extended in the low element of
6967         // a vector.  If Idx != 0, swizzle it into place.
6968         if (Idx != 0) {
6969           SmallVector<int, 4> Mask;
6970           Mask.push_back(Idx);
6971           for (unsigned i = 1; i != VecElts; ++i)
6972             Mask.push_back(i);
6973           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6974                                       &Mask[0]);
6975         }
6976         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6977       }
6978     }
6979
6980     // If we have a constant or non-constant insertion into the low element of
6981     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6982     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6983     // depending on what the source datatype is.
6984     if (Idx == 0) {
6985       if (NumZero == 0)
6986         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6987
6988       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6989           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6990         if (VT.is256BitVector() || VT.is512BitVector()) {
6991           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6992           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6993                              Item, DAG.getIntPtrConstant(0));
6994         }
6995         assert(VT.is128BitVector() && "Expected an SSE value type!");
6996         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6997         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6998         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6999       }
7000
7001       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
7002         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
7003         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
7004         if (VT.is256BitVector()) {
7005           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
7006           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
7007         } else {
7008           assert(VT.is128BitVector() && "Expected an SSE value type!");
7009           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
7010         }
7011         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
7012       }
7013     }
7014
7015     // Is it a vector logical left shift?
7016     if (NumElems == 2 && Idx == 1 &&
7017         X86::isZeroNode(Op.getOperand(0)) &&
7018         !X86::isZeroNode(Op.getOperand(1))) {
7019       unsigned NumBits = VT.getSizeInBits();
7020       return getVShift(true, VT,
7021                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7022                                    VT, Op.getOperand(1)),
7023                        NumBits/2, DAG, *this, dl);
7024     }
7025
7026     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
7027       return SDValue();
7028
7029     // Otherwise, if this is a vector with i32 or f32 elements, and the element
7030     // is a non-constant being inserted into an element other than the low one,
7031     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
7032     // movd/movss) to move this into the low element, then shuffle it into
7033     // place.
7034     if (EVTBits == 32) {
7035       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
7036
7037       // If using the new shuffle lowering, just directly insert this.
7038       if (ExperimentalVectorShuffleLowering)
7039         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
7040
7041       // Turn it into a shuffle of zero and zero-extended scalar to vector.
7042       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
7043       SmallVector<int, 8> MaskVec;
7044       for (unsigned i = 0; i != NumElems; ++i)
7045         MaskVec.push_back(i == Idx ? 0 : 1);
7046       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
7047     }
7048   }
7049
7050   // Splat is obviously ok. Let legalizer expand it to a shuffle.
7051   if (Values.size() == 1) {
7052     if (EVTBits == 32) {
7053       // Instead of a shuffle like this:
7054       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
7055       // Check if it's possible to issue this instead.
7056       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
7057       unsigned Idx = countTrailingZeros(NonZeros);
7058       SDValue Item = Op.getOperand(Idx);
7059       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
7060         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
7061     }
7062     return SDValue();
7063   }
7064
7065   // A vector full of immediates; various special cases are already
7066   // handled, so this is best done with a single constant-pool load.
7067   if (IsAllConstants)
7068     return SDValue();
7069
7070   // For AVX-length vectors, see if we can use a vector load to get all of the
7071   // elements, otherwise build the individual 128-bit pieces and use
7072   // shuffles to put them in place.
7073   if (VT.is256BitVector() || VT.is512BitVector()) {
7074     SmallVector<SDValue, 64> V;
7075     for (unsigned i = 0; i != NumElems; ++i)
7076       V.push_back(Op.getOperand(i));
7077
7078     // Check for a build vector of consecutive loads.
7079     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
7080       return LD;
7081
7082     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
7083
7084     // Build both the lower and upper subvector.
7085     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7086                                 makeArrayRef(&V[0], NumElems/2));
7087     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7088                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
7089
7090     // Recreate the wider vector with the lower and upper part.
7091     if (VT.is256BitVector())
7092       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7093     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7094   }
7095
7096   // Let legalizer expand 2-wide build_vectors.
7097   if (EVTBits == 64) {
7098     if (NumNonZero == 1) {
7099       // One half is zero or undef.
7100       unsigned Idx = countTrailingZeros(NonZeros);
7101       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
7102                                  Op.getOperand(Idx));
7103       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
7104     }
7105     return SDValue();
7106   }
7107
7108   // If element VT is < 32 bits, convert it to inserts into a zero vector.
7109   if (EVTBits == 8 && NumElems == 16) {
7110     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
7111                                         Subtarget, *this);
7112     if (V.getNode()) return V;
7113   }
7114
7115   if (EVTBits == 16 && NumElems == 8) {
7116     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
7117                                       Subtarget, *this);
7118     if (V.getNode()) return V;
7119   }
7120
7121   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
7122   if (EVTBits == 32 && NumElems == 4) {
7123     SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
7124     if (V.getNode())
7125       return V;
7126   }
7127
7128   // If element VT is == 32 bits, turn it into a number of shuffles.
7129   SmallVector<SDValue, 8> V(NumElems);
7130   if (NumElems == 4 && NumZero > 0) {
7131     for (unsigned i = 0; i < 4; ++i) {
7132       bool isZero = !(NonZeros & (1 << i));
7133       if (isZero)
7134         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7135       else
7136         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7137     }
7138
7139     for (unsigned i = 0; i < 2; ++i) {
7140       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7141         default: break;
7142         case 0:
7143           V[i] = V[i*2];  // Must be a zero vector.
7144           break;
7145         case 1:
7146           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7147           break;
7148         case 2:
7149           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7150           break;
7151         case 3:
7152           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7153           break;
7154       }
7155     }
7156
7157     bool Reverse1 = (NonZeros & 0x3) == 2;
7158     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7159     int MaskVec[] = {
7160       Reverse1 ? 1 : 0,
7161       Reverse1 ? 0 : 1,
7162       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7163       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7164     };
7165     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7166   }
7167
7168   if (Values.size() > 1 && VT.is128BitVector()) {
7169     // Check for a build vector of consecutive loads.
7170     for (unsigned i = 0; i < NumElems; ++i)
7171       V[i] = Op.getOperand(i);
7172
7173     // Check for elements which are consecutive loads.
7174     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7175     if (LD.getNode())
7176       return LD;
7177
7178     // Check for a build vector from mostly shuffle plus few inserting.
7179     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7180     if (Sh.getNode())
7181       return Sh;
7182
7183     // For SSE 4.1, use insertps to put the high elements into the low element.
7184     if (Subtarget->hasSSE41()) {
7185       SDValue Result;
7186       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7187         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7188       else
7189         Result = DAG.getUNDEF(VT);
7190
7191       for (unsigned i = 1; i < NumElems; ++i) {
7192         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7193         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7194                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7195       }
7196       return Result;
7197     }
7198
7199     // Otherwise, expand into a number of unpckl*, start by extending each of
7200     // our (non-undef) elements to the full vector width with the element in the
7201     // bottom slot of the vector (which generates no code for SSE).
7202     for (unsigned i = 0; i < NumElems; ++i) {
7203       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7204         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7205       else
7206         V[i] = DAG.getUNDEF(VT);
7207     }
7208
7209     // Next, we iteratively mix elements, e.g. for v4f32:
7210     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7211     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7212     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7213     unsigned EltStride = NumElems >> 1;
7214     while (EltStride != 0) {
7215       for (unsigned i = 0; i < EltStride; ++i) {
7216         // If V[i+EltStride] is undef and this is the first round of mixing,
7217         // then it is safe to just drop this shuffle: V[i] is already in the
7218         // right place, the one element (since it's the first round) being
7219         // inserted as undef can be dropped.  This isn't safe for successive
7220         // rounds because they will permute elements within both vectors.
7221         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7222             EltStride == NumElems/2)
7223           continue;
7224
7225         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7226       }
7227       EltStride >>= 1;
7228     }
7229     return V[0];
7230   }
7231   return SDValue();
7232 }
7233
7234 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7235 // to create 256-bit vectors from two other 128-bit ones.
7236 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7237   SDLoc dl(Op);
7238   MVT ResVT = Op.getSimpleValueType();
7239
7240   assert((ResVT.is256BitVector() ||
7241           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7242
7243   SDValue V1 = Op.getOperand(0);
7244   SDValue V2 = Op.getOperand(1);
7245   unsigned NumElems = ResVT.getVectorNumElements();
7246   if(ResVT.is256BitVector())
7247     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7248
7249   if (Op.getNumOperands() == 4) {
7250     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7251                                 ResVT.getVectorNumElements()/2);
7252     SDValue V3 = Op.getOperand(2);
7253     SDValue V4 = Op.getOperand(3);
7254     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7255       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7256   }
7257   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7258 }
7259
7260 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7261   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7262   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7263          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7264           Op.getNumOperands() == 4)));
7265
7266   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7267   // from two other 128-bit ones.
7268
7269   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7270   return LowerAVXCONCAT_VECTORS(Op, DAG);
7271 }
7272
7273
7274 //===----------------------------------------------------------------------===//
7275 // Vector shuffle lowering
7276 //
7277 // This is an experimental code path for lowering vector shuffles on x86. It is
7278 // designed to handle arbitrary vector shuffles and blends, gracefully
7279 // degrading performance as necessary. It works hard to recognize idiomatic
7280 // shuffles and lower them to optimal instruction patterns without leaving
7281 // a framework that allows reasonably efficient handling of all vector shuffle
7282 // patterns.
7283 //===----------------------------------------------------------------------===//
7284
7285 /// \brief Tiny helper function to identify a no-op mask.
7286 ///
7287 /// This is a somewhat boring predicate function. It checks whether the mask
7288 /// array input, which is assumed to be a single-input shuffle mask of the kind
7289 /// used by the X86 shuffle instructions (not a fully general
7290 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7291 /// in-place shuffle are 'no-op's.
7292 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7293   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7294     if (Mask[i] != -1 && Mask[i] != i)
7295       return false;
7296   return true;
7297 }
7298
7299 /// \brief Helper function to classify a mask as a single-input mask.
7300 ///
7301 /// This isn't a generic single-input test because in the vector shuffle
7302 /// lowering we canonicalize single inputs to be the first input operand. This
7303 /// means we can more quickly test for a single input by only checking whether
7304 /// an input from the second operand exists. We also assume that the size of
7305 /// mask corresponds to the size of the input vectors which isn't true in the
7306 /// fully general case.
7307 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7308   for (int M : Mask)
7309     if (M >= (int)Mask.size())
7310       return false;
7311   return true;
7312 }
7313
7314 /// \brief Test whether there are elements crossing 128-bit lanes in this
7315 /// shuffle mask.
7316 ///
7317 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
7318 /// and we routinely test for these.
7319 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
7320   int LaneSize = 128 / VT.getScalarSizeInBits();
7321   int Size = Mask.size();
7322   for (int i = 0; i < Size; ++i)
7323     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
7324       return true;
7325   return false;
7326 }
7327
7328 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
7329 ///
7330 /// This checks a shuffle mask to see if it is performing the same
7331 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
7332 /// that it is also not lane-crossing. It may however involve a blend from the
7333 /// same lane of a second vector.
7334 ///
7335 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
7336 /// non-trivial to compute in the face of undef lanes. The representation is
7337 /// *not* suitable for use with existing 128-bit shuffles as it will contain
7338 /// entries from both V1 and V2 inputs to the wider mask.
7339 static bool
7340 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7341                                 SmallVectorImpl<int> &RepeatedMask) {
7342   int LaneSize = 128 / VT.getScalarSizeInBits();
7343   RepeatedMask.resize(LaneSize, -1);
7344   int Size = Mask.size();
7345   for (int i = 0; i < Size; ++i) {
7346     if (Mask[i] < 0)
7347       continue;
7348     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
7349       // This entry crosses lanes, so there is no way to model this shuffle.
7350       return false;
7351
7352     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
7353     if (RepeatedMask[i % LaneSize] == -1)
7354       // This is the first non-undef entry in this slot of a 128-bit lane.
7355       RepeatedMask[i % LaneSize] =
7356           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
7357     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
7358       // Found a mismatch with the repeated mask.
7359       return false;
7360   }
7361   return true;
7362 }
7363
7364 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7365 // 2013 will allow us to use it as a non-type template parameter.
7366 namespace {
7367
7368 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7369 ///
7370 /// See its documentation for details.
7371 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7372   if (Mask.size() != Args.size())
7373     return false;
7374   for (int i = 0, e = Mask.size(); i < e; ++i) {
7375     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7376     if (Mask[i] != -1 && Mask[i] != *Args[i])
7377       return false;
7378   }
7379   return true;
7380 }
7381
7382 } // namespace
7383
7384 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7385 /// arguments.
7386 ///
7387 /// This is a fast way to test a shuffle mask against a fixed pattern:
7388 ///
7389 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7390 ///
7391 /// It returns true if the mask is exactly as wide as the argument list, and
7392 /// each element of the mask is either -1 (signifying undef) or the value given
7393 /// in the argument.
7394 static const VariadicFunction1<
7395     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7396
7397 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7398 ///
7399 /// This helper function produces an 8-bit shuffle immediate corresponding to
7400 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7401 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7402 /// example.
7403 ///
7404 /// NB: We rely heavily on "undef" masks preserving the input lane.
7405 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7406                                           SelectionDAG &DAG) {
7407   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7408   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7409   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7410   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7411   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7412
7413   unsigned Imm = 0;
7414   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7415   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7416   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7417   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7418   return DAG.getConstant(Imm, MVT::i8);
7419 }
7420
7421 /// \brief Try to emit a blend instruction for a shuffle.
7422 ///
7423 /// This doesn't do any checks for the availability of instructions for blending
7424 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7425 /// be matched in the backend with the type given. What it does check for is
7426 /// that the shuffle mask is in fact a blend.
7427 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7428                                          SDValue V2, ArrayRef<int> Mask,
7429                                          const X86Subtarget *Subtarget,
7430                                          SelectionDAG &DAG) {
7431
7432   unsigned BlendMask = 0;
7433   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7434     if (Mask[i] >= Size) {
7435       if (Mask[i] != i + Size)
7436         return SDValue(); // Shuffled V2 input!
7437       BlendMask |= 1u << i;
7438       continue;
7439     }
7440     if (Mask[i] >= 0 && Mask[i] != i)
7441       return SDValue(); // Shuffled V1 input!
7442   }
7443   switch (VT.SimpleTy) {
7444   case MVT::v2f64:
7445   case MVT::v4f32:
7446   case MVT::v4f64:
7447   case MVT::v8f32:
7448     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7449                        DAG.getConstant(BlendMask, MVT::i8));
7450
7451   case MVT::v4i64:
7452   case MVT::v8i32:
7453     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7454     // FALLTHROUGH
7455   case MVT::v2i64:
7456   case MVT::v4i32:
7457     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7458     // that instruction.
7459     if (Subtarget->hasAVX2()) {
7460       // Scale the blend by the number of 32-bit dwords per element.
7461       int Scale =  VT.getScalarSizeInBits() / 32;
7462       BlendMask = 0;
7463       for (int i = 0, Size = Mask.size(); i < Size; ++i)
7464         if (Mask[i] >= Size)
7465           for (int j = 0; j < Scale; ++j)
7466             BlendMask |= 1u << (i * Scale + j);
7467
7468       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7469       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
7470       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
7471       return DAG.getNode(ISD::BITCAST, DL, VT,
7472                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7473                                      DAG.getConstant(BlendMask, MVT::i8)));
7474     }
7475     // FALLTHROUGH
7476   case MVT::v8i16: {
7477     // For integer shuffles we need to expand the mask and cast the inputs to
7478     // v8i16s prior to blending.
7479     int Scale = 8 / VT.getVectorNumElements();
7480     BlendMask = 0;
7481     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7482       if (Mask[i] >= Size)
7483         for (int j = 0; j < Scale; ++j)
7484           BlendMask |= 1u << (i * Scale + j);
7485
7486     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7487     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7488     return DAG.getNode(ISD::BITCAST, DL, VT,
7489                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7490                                    DAG.getConstant(BlendMask, MVT::i8)));
7491   }
7492
7493   case MVT::v16i16: {
7494     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7495     SmallVector<int, 8> RepeatedMask;
7496     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7497       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7498       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7499       BlendMask = 0;
7500       for (int i = 0; i < 8; ++i)
7501         if (RepeatedMask[i] >= 16)
7502           BlendMask |= 1u << i;
7503       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7504                          DAG.getConstant(BlendMask, MVT::i8));
7505     }
7506   }
7507     // FALLTHROUGH
7508   case MVT::v32i8: {
7509     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7510     // Scale the blend by the number of bytes per element.
7511     int Scale =  VT.getScalarSizeInBits() / 8;
7512     assert(Mask.size() * Scale == 32 && "Not a 256-bit vector!");
7513
7514     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7515     // mix of LLVM's code generator and the x86 backend. We tell the code
7516     // generator that boolean values in the elements of an x86 vector register
7517     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7518     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7519     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7520     // of the element (the remaining are ignored) and 0 in that high bit would
7521     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7522     // the LLVM model for boolean values in vector elements gets the relevant
7523     // bit set, it is set backwards and over constrained relative to x86's
7524     // actual model.
7525     SDValue VSELECTMask[32];
7526     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7527       for (int j = 0; j < Scale; ++j)
7528         VSELECTMask[Scale * i + j] =
7529             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7530                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8);
7531
7532     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1);
7533     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V2);
7534     return DAG.getNode(
7535         ISD::BITCAST, DL, VT,
7536         DAG.getNode(ISD::VSELECT, DL, MVT::v32i8,
7537                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, VSELECTMask),
7538                     V1, V2));
7539   }
7540
7541   default:
7542     llvm_unreachable("Not a supported integer vector type!");
7543   }
7544 }
7545
7546 /// \brief Try to lower as a blend of elements from two inputs followed by
7547 /// a single-input permutation.
7548 ///
7549 /// This matches the pattern where we can blend elements from two inputs and
7550 /// then reduce the shuffle to a single-input permutation.
7551 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7552                                                    SDValue V2,
7553                                                    ArrayRef<int> Mask,
7554                                                    SelectionDAG &DAG) {
7555   // We build up the blend mask while checking whether a blend is a viable way
7556   // to reduce the shuffle.
7557   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7558   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7559
7560   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7561     if (Mask[i] < 0)
7562       continue;
7563
7564     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7565
7566     if (BlendMask[Mask[i] % Size] == -1)
7567       BlendMask[Mask[i] % Size] = Mask[i];
7568     else if (BlendMask[Mask[i] % Size] != Mask[i])
7569       return SDValue(); // Can't blend in the needed input!
7570
7571     PermuteMask[i] = Mask[i] % Size;
7572   }
7573
7574   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7575   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7576 }
7577
7578 /// \brief Generic routine to lower a shuffle and blend as a decomposed set of
7579 /// unblended shuffles followed by an unshuffled blend.
7580 ///
7581 /// This matches the extremely common pattern for handling combined
7582 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7583 /// operations.
7584 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7585                                                           SDValue V1,
7586                                                           SDValue V2,
7587                                                           ArrayRef<int> Mask,
7588                                                           SelectionDAG &DAG) {
7589   // Shuffle the input elements into the desired positions in V1 and V2 and
7590   // blend them together.
7591   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7592   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7593   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7594   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7595     if (Mask[i] >= 0 && Mask[i] < Size) {
7596       V1Mask[i] = Mask[i];
7597       BlendMask[i] = i;
7598     } else if (Mask[i] >= Size) {
7599       V2Mask[i] = Mask[i] - Size;
7600       BlendMask[i] = i + Size;
7601     }
7602
7603   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7604   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7605   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7606 }
7607
7608 /// \brief Try to lower a vector shuffle as a byte rotation.
7609 ///
7610 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7611 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7612 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7613 /// try to generically lower a vector shuffle through such an pattern. It
7614 /// does not check for the profitability of lowering either as PALIGNR or
7615 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7616 /// This matches shuffle vectors that look like:
7617 ///
7618 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7619 ///
7620 /// Essentially it concatenates V1 and V2, shifts right by some number of
7621 /// elements, and takes the low elements as the result. Note that while this is
7622 /// specified as a *right shift* because x86 is little-endian, it is a *left
7623 /// rotate* of the vector lanes.
7624 ///
7625 /// Note that this only handles 128-bit vector widths currently.
7626 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7627                                               SDValue V2,
7628                                               ArrayRef<int> Mask,
7629                                               const X86Subtarget *Subtarget,
7630                                               SelectionDAG &DAG) {
7631   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7632
7633   // We need to detect various ways of spelling a rotation:
7634   //   [11, 12, 13, 14, 15,  0,  1,  2]
7635   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7636   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7637   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7638   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7639   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7640   int Rotation = 0;
7641   SDValue Lo, Hi;
7642   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7643     if (Mask[i] == -1)
7644       continue;
7645     assert(Mask[i] >= 0 && "Only -1 is a valid negative mask element!");
7646
7647     // Based on the mod-Size value of this mask element determine where
7648     // a rotated vector would have started.
7649     int StartIdx = i - (Mask[i] % Size);
7650     if (StartIdx == 0)
7651       // The identity rotation isn't interesting, stop.
7652       return SDValue();
7653
7654     // If we found the tail of a vector the rotation must be the missing
7655     // front. If we found the head of a vector, it must be how much of the head.
7656     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
7657
7658     if (Rotation == 0)
7659       Rotation = CandidateRotation;
7660     else if (Rotation != CandidateRotation)
7661       // The rotations don't match, so we can't match this mask.
7662       return SDValue();
7663
7664     // Compute which value this mask is pointing at.
7665     SDValue MaskV = Mask[i] < Size ? V1 : V2;
7666
7667     // Compute which of the two target values this index should be assigned to.
7668     // This reflects whether the high elements are remaining or the low elements
7669     // are remaining.
7670     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7671
7672     // Either set up this value if we've not encountered it before, or check
7673     // that it remains consistent.
7674     if (!TargetV)
7675       TargetV = MaskV;
7676     else if (TargetV != MaskV)
7677       // This may be a rotation, but it pulls from the inputs in some
7678       // unsupported interleaving.
7679       return SDValue();
7680   }
7681
7682   // Check that we successfully analyzed the mask, and normalize the results.
7683   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7684   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7685   if (!Lo)
7686     Lo = Hi;
7687   else if (!Hi)
7688     Hi = Lo;
7689
7690   assert(VT.getSizeInBits() == 128 &&
7691          "Rotate-based lowering only supports 128-bit lowering!");
7692   assert(Mask.size() <= 16 &&
7693          "Can shuffle at most 16 bytes in a 128-bit vector!");
7694
7695   // The actual rotate instruction rotates bytes, so we need to scale the
7696   // rotation based on how many bytes are in the vector.
7697   int Scale = 16 / Mask.size();
7698
7699   // SSSE3 targets can use the palignr instruction
7700   if (Subtarget->hasSSSE3()) {
7701     // Cast the inputs to v16i8 to match PALIGNR.
7702     Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Lo);
7703     Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Hi);
7704
7705     return DAG.getNode(ISD::BITCAST, DL, VT,
7706                        DAG.getNode(X86ISD::PALIGNR, DL, MVT::v16i8, Hi, Lo,
7707                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
7708   }
7709
7710   // Default SSE2 implementation
7711   int LoByteShift = 16 - Rotation * Scale;
7712   int HiByteShift = Rotation * Scale;
7713
7714   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7715   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
7716   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
7717
7718   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7719                                 DAG.getConstant(8 * LoByteShift, MVT::i8));
7720   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7721                                 DAG.getConstant(8 * HiByteShift, MVT::i8));
7722   return DAG.getNode(ISD::BITCAST, DL, VT,
7723                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7724 }
7725
7726 /// \brief Compute whether each element of a shuffle is zeroable.
7727 ///
7728 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7729 /// Either it is an undef element in the shuffle mask, the element of the input
7730 /// referenced is undef, or the element of the input referenced is known to be
7731 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7732 /// as many lanes with this technique as possible to simplify the remaining
7733 /// shuffle.
7734 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7735                                                      SDValue V1, SDValue V2) {
7736   SmallBitVector Zeroable(Mask.size(), false);
7737
7738   while (V1.getOpcode() == ISD::BITCAST)
7739     V1 = V1->getOperand(0);
7740   while (V2.getOpcode() == ISD::BITCAST)
7741     V2 = V2->getOperand(0);
7742
7743   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7744   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7745
7746   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7747     int M = Mask[i];
7748     // Handle the easy cases.
7749     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7750       Zeroable[i] = true;
7751       continue;
7752     }
7753
7754     // If this is an index into a build_vector node (which has the same number
7755     // of elements), dig out the input value and use it.
7756     SDValue V = M < Size ? V1 : V2;
7757     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
7758       continue;
7759
7760     SDValue Input = V.getOperand(M % Size);
7761     // The UNDEF opcode check really should be dead code here, but not quite
7762     // worth asserting on (it isn't invalid, just unexpected).
7763     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
7764       Zeroable[i] = true;
7765   }
7766
7767   return Zeroable;
7768 }
7769
7770 /// \brief Try to emit a bitmask instruction for a shuffle.
7771 ///
7772 /// This handles cases where we can model a blend exactly as a bitmask due to
7773 /// one of the inputs being zeroable.
7774 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
7775                                            SDValue V2, ArrayRef<int> Mask,
7776                                            SelectionDAG &DAG) {
7777   MVT EltVT = VT.getScalarType();
7778   int NumEltBits = EltVT.getSizeInBits();
7779   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
7780   SDValue Zero = DAG.getConstant(0, IntEltVT);
7781   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
7782   if (EltVT.isFloatingPoint()) {
7783     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
7784     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
7785   }
7786   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
7787   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7788   SDValue V;
7789   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7790     if (Zeroable[i])
7791       continue;
7792     if (Mask[i] % Size != i)
7793       return SDValue(); // Not a blend.
7794     if (!V)
7795       V = Mask[i] < Size ? V1 : V2;
7796     else if (V != (Mask[i] < Size ? V1 : V2))
7797       return SDValue(); // Can only let one input through the mask.
7798
7799     VMaskOps[i] = AllOnes;
7800   }
7801   if (!V)
7802     return SDValue(); // No non-zeroable elements!
7803
7804   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7805   V = DAG.getNode(VT.isFloatingPoint()
7806                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7807                   DL, VT, V, VMask);
7808   return V;
7809 }
7810
7811 /// \brief Try to lower a vector shuffle as a byte shift (shifts in zeros).
7812 ///
7813 /// Attempts to match a shuffle mask against the PSRLDQ and PSLLDQ SSE2
7814 /// byte-shift instructions. The mask must consist of a shifted sequential
7815 /// shuffle from one of the input vectors and zeroable elements for the
7816 /// remaining 'shifted in' elements.
7817 ///
7818 /// Note that this only handles 128-bit vector widths currently.
7819 static SDValue lowerVectorShuffleAsByteShift(SDLoc DL, MVT VT, SDValue V1,
7820                                              SDValue V2, ArrayRef<int> Mask,
7821                                              SelectionDAG &DAG) {
7822   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7823
7824   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7825
7826   int Size = Mask.size();
7827   int Scale = 16 / Size;
7828
7829   for (int Shift = 1; Shift < Size; Shift++) {
7830     int ByteShift = Shift * Scale;
7831
7832     // PSRLDQ : (little-endian) right byte shift
7833     // [ 5,  6,  7, zz, zz, zz, zz, zz]
7834     // [ -1, 5,  6,  7, zz, zz, zz, zz]
7835     // [  1, 2, -1, -1, -1, -1, zz, zz]
7836     bool ZeroableRight = true;
7837     for (int i = Size - Shift; i < Size; i++) {
7838       ZeroableRight &= Zeroable[i];
7839     }
7840
7841     if (ZeroableRight) {
7842       bool ValidShiftRight1 =
7843           isSequentialOrUndefInRange(Mask, 0, Size - Shift, Shift);
7844       bool ValidShiftRight2 =
7845           isSequentialOrUndefInRange(Mask, 0, Size - Shift, Size + Shift);
7846
7847       if (ValidShiftRight1 || ValidShiftRight2) {
7848         // Cast the inputs to v2i64 to match PSRLDQ.
7849         SDValue &TargetV = ValidShiftRight1 ? V1 : V2;
7850         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7851         SDValue Shifted = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, V,
7852                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7853         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7854       }
7855     }
7856
7857     // PSLLDQ : (little-endian) left byte shift
7858     // [ zz,  0,  1,  2,  3,  4,  5,  6]
7859     // [ zz, zz, -1, -1,  2,  3,  4, -1]
7860     // [ zz, zz, zz, zz, zz, zz, -1,  1]
7861     bool ZeroableLeft = true;
7862     for (int i = 0; i < Shift; i++) {
7863       ZeroableLeft &= Zeroable[i];
7864     }
7865
7866     if (ZeroableLeft) {
7867       bool ValidShiftLeft1 =
7868           isSequentialOrUndefInRange(Mask, Shift, Size - Shift, 0);
7869       bool ValidShiftLeft2 =
7870           isSequentialOrUndefInRange(Mask, Shift, Size - Shift, Size);
7871
7872       if (ValidShiftLeft1 || ValidShiftLeft2) {
7873         // Cast the inputs to v2i64 to match PSLLDQ.
7874         SDValue &TargetV = ValidShiftLeft1 ? V1 : V2;
7875         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7876         SDValue Shifted = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, V,
7877                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7878         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7879       }
7880     }
7881   }
7882
7883   return SDValue();
7884 }
7885
7886 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7887 ///
7888 /// Attempts to match a shuffle mask against the PSRL(W/D/Q) and PSLL(W/D/Q)
7889 /// SSE2 and AVX2 logical bit-shift instructions. The function matches
7890 /// elements from one of the input vectors shuffled to the left or right
7891 /// with zeroable elements 'shifted in'.
7892 static SDValue lowerVectorShuffleAsBitShift(SDLoc DL, MVT VT, SDValue V1,
7893                                             SDValue V2, ArrayRef<int> Mask,
7894                                             SelectionDAG &DAG) {
7895   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7896
7897   int Size = Mask.size();
7898   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7899
7900   // PSRL : (little-endian) right bit shift.
7901   // [  1, zz,  3, zz]
7902   // [ -1, -1,  7, zz]
7903   // PSHL : (little-endian) left bit shift.
7904   // [ zz, 0, zz,  2 ]
7905   // [ -1, 4, zz, -1 ]
7906   auto MatchBitShift = [&](int Shift, int Scale) -> SDValue {
7907     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7908     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7909     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7910            "Illegal integer vector type");
7911
7912     bool MatchLeft = true, MatchRight = true;
7913     for (int i = 0; i != Size; i += Scale) {
7914       for (int j = 0; j != Shift; j++) {
7915         MatchLeft &= Zeroable[i + j];
7916       }
7917       for (int j = Scale - Shift; j != Scale; j++) {
7918         MatchRight &= Zeroable[i + j];
7919       }
7920     }
7921     if (!(MatchLeft || MatchRight))
7922       return SDValue();
7923
7924     bool MatchV1 = true, MatchV2 = true;
7925     for (int i = 0; i != Size; i += Scale) {
7926       unsigned Pos = MatchLeft ? i + Shift : i;
7927       unsigned Low = MatchLeft ? i : i + Shift;
7928       unsigned Len = Scale - Shift;
7929       MatchV1 &= isSequentialOrUndefInRange(Mask, Pos, Len, Low);
7930       MatchV2 &= isSequentialOrUndefInRange(Mask, Pos, Len, Low + Size);
7931     }
7932     if (!(MatchV1 || MatchV2))
7933       return SDValue();
7934
7935     // Cast the inputs to ShiftVT to match VSRLI/VSHLI and back again.
7936     unsigned OpCode = MatchLeft ? X86ISD::VSHLI : X86ISD::VSRLI;
7937     int ShiftAmt = Shift * VT.getScalarSizeInBits();
7938     SDValue V = MatchV1 ? V1 : V2;
7939     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
7940     V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
7941     return DAG.getNode(ISD::BITCAST, DL, VT, V);
7942   };
7943
7944   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7945   // keep doubling the size of the integer elements up to that. We can
7946   // then shift the elements of the integer vector by whole multiples of
7947   // their width within the elements of the larger integer vector. Test each
7948   // multiple to see if we can find a match with the moved element indices
7949   // and that the shifted in elements are all zeroable.
7950   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 64; Scale *= 2)
7951     for (int Shift = 1; Shift != Scale; Shift++)
7952       if (SDValue BitShift = MatchBitShift(Shift, Scale))
7953         return BitShift;
7954
7955   // no match
7956   return SDValue();
7957 }
7958
7959 /// \brief Lower a vector shuffle as a zero or any extension.
7960 ///
7961 /// Given a specific number of elements, element bit width, and extension
7962 /// stride, produce either a zero or any extension based on the available
7963 /// features of the subtarget.
7964 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7965     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7966     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7967   assert(Scale > 1 && "Need a scale to extend.");
7968   int NumElements = VT.getVectorNumElements();
7969   int EltBits = VT.getScalarSizeInBits();
7970   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7971          "Only 8, 16, and 32 bit elements can be extended.");
7972   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7973
7974   // Found a valid zext mask! Try various lowering strategies based on the
7975   // input type and available ISA extensions.
7976   if (Subtarget->hasSSE41()) {
7977     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7978                                  NumElements / Scale);
7979     return DAG.getNode(ISD::BITCAST, DL, VT,
7980                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7981   }
7982
7983   // For any extends we can cheat for larger element sizes and use shuffle
7984   // instructions that can fold with a load and/or copy.
7985   if (AnyExt && EltBits == 32) {
7986     int PSHUFDMask[4] = {0, -1, 1, -1};
7987     return DAG.getNode(
7988         ISD::BITCAST, DL, VT,
7989         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7990                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7991                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7992   }
7993   if (AnyExt && EltBits == 16 && Scale > 2) {
7994     int PSHUFDMask[4] = {0, -1, 0, -1};
7995     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7996                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7997                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
7998     int PSHUFHWMask[4] = {1, -1, -1, -1};
7999     return DAG.getNode(
8000         ISD::BITCAST, DL, VT,
8001         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
8002                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
8003                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
8004   }
8005
8006   // If this would require more than 2 unpack instructions to expand, use
8007   // pshufb when available. We can only use more than 2 unpack instructions
8008   // when zero extending i8 elements which also makes it easier to use pshufb.
8009   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
8010     assert(NumElements == 16 && "Unexpected byte vector width!");
8011     SDValue PSHUFBMask[16];
8012     for (int i = 0; i < 16; ++i)
8013       PSHUFBMask[i] =
8014           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
8015     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
8016     return DAG.getNode(ISD::BITCAST, DL, VT,
8017                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
8018                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
8019                                                MVT::v16i8, PSHUFBMask)));
8020   }
8021
8022   // Otherwise emit a sequence of unpacks.
8023   do {
8024     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
8025     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
8026                          : getZeroVector(InputVT, Subtarget, DAG, DL);
8027     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
8028     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
8029     Scale /= 2;
8030     EltBits *= 2;
8031     NumElements /= 2;
8032   } while (Scale > 1);
8033   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
8034 }
8035
8036 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
8037 ///
8038 /// This routine will try to do everything in its power to cleverly lower
8039 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
8040 /// check for the profitability of this lowering,  it tries to aggressively
8041 /// match this pattern. It will use all of the micro-architectural details it
8042 /// can to emit an efficient lowering. It handles both blends with all-zero
8043 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
8044 /// masking out later).
8045 ///
8046 /// The reason we have dedicated lowering for zext-style shuffles is that they
8047 /// are both incredibly common and often quite performance sensitive.
8048 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
8049     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
8050     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8051   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8052
8053   int Bits = VT.getSizeInBits();
8054   int NumElements = VT.getVectorNumElements();
8055   assert(VT.getScalarSizeInBits() <= 32 &&
8056          "Exceeds 32-bit integer zero extension limit");
8057   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
8058
8059   // Define a helper function to check a particular ext-scale and lower to it if
8060   // valid.
8061   auto Lower = [&](int Scale) -> SDValue {
8062     SDValue InputV;
8063     bool AnyExt = true;
8064     for (int i = 0; i < NumElements; ++i) {
8065       if (Mask[i] == -1)
8066         continue; // Valid anywhere but doesn't tell us anything.
8067       if (i % Scale != 0) {
8068         // Each of the extended elements need to be zeroable.
8069         if (!Zeroable[i])
8070           return SDValue();
8071
8072         // We no longer are in the anyext case.
8073         AnyExt = false;
8074         continue;
8075       }
8076
8077       // Each of the base elements needs to be consecutive indices into the
8078       // same input vector.
8079       SDValue V = Mask[i] < NumElements ? V1 : V2;
8080       if (!InputV)
8081         InputV = V;
8082       else if (InputV != V)
8083         return SDValue(); // Flip-flopping inputs.
8084
8085       if (Mask[i] % NumElements != i / Scale)
8086         return SDValue(); // Non-consecutive strided elements.
8087     }
8088
8089     // If we fail to find an input, we have a zero-shuffle which should always
8090     // have already been handled.
8091     // FIXME: Maybe handle this here in case during blending we end up with one?
8092     if (!InputV)
8093       return SDValue();
8094
8095     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
8096         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
8097   };
8098
8099   // The widest scale possible for extending is to a 64-bit integer.
8100   assert(Bits % 64 == 0 &&
8101          "The number of bits in a vector must be divisible by 64 on x86!");
8102   int NumExtElements = Bits / 64;
8103
8104   // Each iteration, try extending the elements half as much, but into twice as
8105   // many elements.
8106   for (; NumExtElements < NumElements; NumExtElements *= 2) {
8107     assert(NumElements % NumExtElements == 0 &&
8108            "The input vector size must be divisible by the extended size.");
8109     if (SDValue V = Lower(NumElements / NumExtElements))
8110       return V;
8111   }
8112
8113   // General extends failed, but 128-bit vectors may be able to use MOVQ.
8114   if (Bits != 128)
8115     return SDValue();
8116
8117   // Returns one of the source operands if the shuffle can be reduced to a
8118   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
8119   auto CanZExtLowHalf = [&]() {
8120     for (int i = NumElements / 2; i != NumElements; i++)
8121       if (!Zeroable[i])
8122         return SDValue();
8123     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
8124       return V1;
8125     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
8126       return V2;
8127     return SDValue();
8128   };
8129
8130   if (SDValue V = CanZExtLowHalf()) {
8131     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
8132     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
8133     return DAG.getNode(ISD::BITCAST, DL, VT, V);
8134   }
8135
8136   // No viable ext lowering found.
8137   return SDValue();
8138 }
8139
8140 /// \brief Try to get a scalar value for a specific element of a vector.
8141 ///
8142 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
8143 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
8144                                               SelectionDAG &DAG) {
8145   MVT VT = V.getSimpleValueType();
8146   MVT EltVT = VT.getVectorElementType();
8147   while (V.getOpcode() == ISD::BITCAST)
8148     V = V.getOperand(0);
8149   // If the bitcasts shift the element size, we can't extract an equivalent
8150   // element from it.
8151   MVT NewVT = V.getSimpleValueType();
8152   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
8153     return SDValue();
8154
8155   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8156       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
8157     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
8158
8159   return SDValue();
8160 }
8161
8162 /// \brief Helper to test for a load that can be folded with x86 shuffles.
8163 ///
8164 /// This is particularly important because the set of instructions varies
8165 /// significantly based on whether the operand is a load or not.
8166 static bool isShuffleFoldableLoad(SDValue V) {
8167   while (V.getOpcode() == ISD::BITCAST)
8168     V = V.getOperand(0);
8169
8170   return ISD::isNON_EXTLoad(V.getNode());
8171 }
8172
8173 /// \brief Try to lower insertion of a single element into a zero vector.
8174 ///
8175 /// This is a common pattern that we have especially efficient patterns to lower
8176 /// across all subtarget feature sets.
8177 static SDValue lowerVectorShuffleAsElementInsertion(
8178     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
8179     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8180   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8181   MVT ExtVT = VT;
8182   MVT EltVT = VT.getVectorElementType();
8183
8184   int V2Index = std::find_if(Mask.begin(), Mask.end(),
8185                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
8186                 Mask.begin();
8187   bool IsV1Zeroable = true;
8188   for (int i = 0, Size = Mask.size(); i < Size; ++i)
8189     if (i != V2Index && !Zeroable[i]) {
8190       IsV1Zeroable = false;
8191       break;
8192     }
8193
8194   // Check for a single input from a SCALAR_TO_VECTOR node.
8195   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
8196   // all the smarts here sunk into that routine. However, the current
8197   // lowering of BUILD_VECTOR makes that nearly impossible until the old
8198   // vector shuffle lowering is dead.
8199   if (SDValue V2S = getScalarValueForVectorElement(
8200           V2, Mask[V2Index] - Mask.size(), DAG)) {
8201     // We need to zext the scalar if it is smaller than an i32.
8202     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
8203     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
8204       // Using zext to expand a narrow element won't work for non-zero
8205       // insertions.
8206       if (!IsV1Zeroable)
8207         return SDValue();
8208
8209       // Zero-extend directly to i32.
8210       ExtVT = MVT::v4i32;
8211       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
8212     }
8213     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8214   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8215              EltVT == MVT::i16) {
8216     // Either not inserting from the low element of the input or the input
8217     // element size is too small to use VZEXT_MOVL to clear the high bits.
8218     return SDValue();
8219   }
8220
8221   if (!IsV1Zeroable) {
8222     // If V1 can't be treated as a zero vector we have fewer options to lower
8223     // this. We can't support integer vectors or non-zero targets cheaply, and
8224     // the V1 elements can't be permuted in any way.
8225     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8226     if (!VT.isFloatingPoint() || V2Index != 0)
8227       return SDValue();
8228     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8229     V1Mask[V2Index] = -1;
8230     if (!isNoopShuffleMask(V1Mask))
8231       return SDValue();
8232     // This is essentially a special case blend operation, but if we have
8233     // general purpose blend operations, they are always faster. Bail and let
8234     // the rest of the lowering handle these as blends.
8235     if (Subtarget->hasSSE41())
8236       return SDValue();
8237
8238     // Otherwise, use MOVSD or MOVSS.
8239     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8240            "Only two types of floating point element types to handle!");
8241     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8242                        ExtVT, V1, V2);
8243   }
8244
8245   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8246   if (ExtVT != VT)
8247     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8248
8249   if (V2Index != 0) {
8250     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8251     // the desired position. Otherwise it is more efficient to do a vector
8252     // shift left. We know that we can do a vector shift left because all
8253     // the inputs are zero.
8254     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8255       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8256       V2Shuffle[V2Index] = 0;
8257       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8258     } else {
8259       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
8260       V2 = DAG.getNode(
8261           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8262           DAG.getConstant(
8263               V2Index * EltVT.getSizeInBits(),
8264               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
8265       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8266     }
8267   }
8268   return V2;
8269 }
8270
8271 /// \brief Try to lower broadcast of a single element.
8272 ///
8273 /// For convenience, this code also bundles all of the subtarget feature set
8274 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8275 /// a convenient way to factor it out.
8276 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
8277                                              ArrayRef<int> Mask,
8278                                              const X86Subtarget *Subtarget,
8279                                              SelectionDAG &DAG) {
8280   if (!Subtarget->hasAVX())
8281     return SDValue();
8282   if (VT.isInteger() && !Subtarget->hasAVX2())
8283     return SDValue();
8284
8285   // Check that the mask is a broadcast.
8286   int BroadcastIdx = -1;
8287   for (int M : Mask)
8288     if (M >= 0 && BroadcastIdx == -1)
8289       BroadcastIdx = M;
8290     else if (M >= 0 && M != BroadcastIdx)
8291       return SDValue();
8292
8293   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8294                                             "a sorted mask where the broadcast "
8295                                             "comes from V1.");
8296
8297   // Go up the chain of (vector) values to try and find a scalar load that
8298   // we can combine with the broadcast.
8299   for (;;) {
8300     switch (V.getOpcode()) {
8301     case ISD::CONCAT_VECTORS: {
8302       int OperandSize = Mask.size() / V.getNumOperands();
8303       V = V.getOperand(BroadcastIdx / OperandSize);
8304       BroadcastIdx %= OperandSize;
8305       continue;
8306     }
8307
8308     case ISD::INSERT_SUBVECTOR: {
8309       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8310       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8311       if (!ConstantIdx)
8312         break;
8313
8314       int BeginIdx = (int)ConstantIdx->getZExtValue();
8315       int EndIdx =
8316           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
8317       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8318         BroadcastIdx -= BeginIdx;
8319         V = VInner;
8320       } else {
8321         V = VOuter;
8322       }
8323       continue;
8324     }
8325     }
8326     break;
8327   }
8328
8329   // Check if this is a broadcast of a scalar. We special case lowering
8330   // for scalars so that we can more effectively fold with loads.
8331   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8332       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8333     V = V.getOperand(BroadcastIdx);
8334
8335     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
8336     // AVX2.
8337     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8338       return SDValue();
8339   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8340     // We can't broadcast from a vector register w/o AVX2, and we can only
8341     // broadcast from the zero-element of a vector register.
8342     return SDValue();
8343   }
8344
8345   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8346 }
8347
8348 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8349 // INSERTPS when the V1 elements are already in the correct locations
8350 // because otherwise we can just always use two SHUFPS instructions which
8351 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8352 // perform INSERTPS if a single V1 element is out of place and all V2
8353 // elements are zeroable.
8354 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8355                                             ArrayRef<int> Mask,
8356                                             SelectionDAG &DAG) {
8357   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8358   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8359   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8360   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8361
8362   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8363
8364   unsigned ZMask = 0;
8365   int V1DstIndex = -1;
8366   int V2DstIndex = -1;
8367   bool V1UsedInPlace = false;
8368
8369   for (int i = 0; i < 4; i++) {
8370     // Synthesize a zero mask from the zeroable elements (includes undefs).
8371     if (Zeroable[i]) {
8372       ZMask |= 1 << i;
8373       continue;
8374     }
8375
8376     // Flag if we use any V1 inputs in place.
8377     if (i == Mask[i]) {
8378       V1UsedInPlace = true;
8379       continue;
8380     }
8381
8382     // We can only insert a single non-zeroable element.
8383     if (V1DstIndex != -1 || V2DstIndex != -1)
8384       return SDValue();
8385
8386     if (Mask[i] < 4) {
8387       // V1 input out of place for insertion.
8388       V1DstIndex = i;
8389     } else {
8390       // V2 input for insertion.
8391       V2DstIndex = i;
8392     }
8393   }
8394
8395   // Don't bother if we have no (non-zeroable) element for insertion.
8396   if (V1DstIndex == -1 && V2DstIndex == -1)
8397     return SDValue();
8398
8399   // Determine element insertion src/dst indices. The src index is from the
8400   // start of the inserted vector, not the start of the concatenated vector.
8401   unsigned V2SrcIndex = 0;
8402   if (V1DstIndex != -1) {
8403     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8404     // and don't use the original V2 at all.
8405     V2SrcIndex = Mask[V1DstIndex];
8406     V2DstIndex = V1DstIndex;
8407     V2 = V1;
8408   } else {
8409     V2SrcIndex = Mask[V2DstIndex] - 4;
8410   }
8411
8412   // If no V1 inputs are used in place, then the result is created only from
8413   // the zero mask and the V2 insertion - so remove V1 dependency.
8414   if (!V1UsedInPlace)
8415     V1 = DAG.getUNDEF(MVT::v4f32);
8416
8417   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8418   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8419
8420   // Insert the V2 element into the desired position.
8421   SDLoc DL(Op);
8422   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8423                      DAG.getConstant(InsertPSMask, MVT::i8));
8424 }
8425
8426 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8427 ///
8428 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8429 /// support for floating point shuffles but not integer shuffles. These
8430 /// instructions will incur a domain crossing penalty on some chips though so
8431 /// it is better to avoid lowering through this for integer vectors where
8432 /// possible.
8433 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8434                                        const X86Subtarget *Subtarget,
8435                                        SelectionDAG &DAG) {
8436   SDLoc DL(Op);
8437   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8438   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8439   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8440   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8441   ArrayRef<int> Mask = SVOp->getMask();
8442   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8443
8444   if (isSingleInputShuffleMask(Mask)) {
8445     // Use low duplicate instructions for masks that match their pattern.
8446     if (Subtarget->hasSSE3())
8447       if (isShuffleEquivalent(Mask, 0, 0))
8448         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8449
8450     // Straight shuffle of a single input vector. Simulate this by using the
8451     // single input as both of the "inputs" to this instruction..
8452     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8453
8454     if (Subtarget->hasAVX()) {
8455       // If we have AVX, we can use VPERMILPS which will allow folding a load
8456       // into the shuffle.
8457       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8458                          DAG.getConstant(SHUFPDMask, MVT::i8));
8459     }
8460
8461     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
8462                        DAG.getConstant(SHUFPDMask, MVT::i8));
8463   }
8464   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8465   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8466
8467   // Use dedicated unpack instructions for masks that match their pattern.
8468   if (isShuffleEquivalent(Mask, 0, 2))
8469     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8470   if (isShuffleEquivalent(Mask, 1, 3))
8471     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8472
8473   // If we have a single input, insert that into V1 if we can do so cheaply.
8474   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8475     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8476             MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
8477       return Insertion;
8478     // Try inverting the insertion since for v2 masks it is easy to do and we
8479     // can't reliably sort the mask one way or the other.
8480     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8481                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8482     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8483             MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
8484       return Insertion;
8485   }
8486
8487   // Try to use one of the special instruction patterns to handle two common
8488   // blend patterns if a zero-blend above didn't work.
8489   if (isShuffleEquivalent(Mask, 0, 3) || isShuffleEquivalent(Mask, 1, 3))
8490     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8491       // We can either use a special instruction to load over the low double or
8492       // to move just the low double.
8493       return DAG.getNode(
8494           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8495           DL, MVT::v2f64, V2,
8496           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8497
8498   if (Subtarget->hasSSE41())
8499     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8500                                                   Subtarget, DAG))
8501       return Blend;
8502
8503   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8504   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
8505                      DAG.getConstant(SHUFPDMask, MVT::i8));
8506 }
8507
8508 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8509 ///
8510 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8511 /// the integer unit to minimize domain crossing penalties. However, for blends
8512 /// it falls back to the floating point shuffle operation with appropriate bit
8513 /// casting.
8514 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8515                                        const X86Subtarget *Subtarget,
8516                                        SelectionDAG &DAG) {
8517   SDLoc DL(Op);
8518   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8519   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8520   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8521   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8522   ArrayRef<int> Mask = SVOp->getMask();
8523   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8524
8525   if (isSingleInputShuffleMask(Mask)) {
8526     // Check for being able to broadcast a single element.
8527     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
8528                                                           Mask, Subtarget, DAG))
8529       return Broadcast;
8530
8531     // Straight shuffle of a single input vector. For everything from SSE2
8532     // onward this has a single fast instruction with no scary immediates.
8533     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8534     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
8535     int WidenedMask[4] = {
8536         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8537         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8538     return DAG.getNode(
8539         ISD::BITCAST, DL, MVT::v2i64,
8540         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
8541                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
8542   }
8543
8544   // Try to use byte shift instructions.
8545   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8546           DL, MVT::v2i64, V1, V2, Mask, DAG))
8547     return Shift;
8548
8549   // If we have a single input from V2 insert that into V1 if we can do so
8550   // cheaply.
8551   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8552     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8553             MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
8554       return Insertion;
8555     // Try inverting the insertion since for v2 masks it is easy to do and we
8556     // can't reliably sort the mask one way or the other.
8557     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8558                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8559     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8560             MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
8561       return Insertion;
8562   }
8563
8564   // Use dedicated unpack instructions for masks that match their pattern.
8565   if (isShuffleEquivalent(Mask, 0, 2))
8566     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8567   if (isShuffleEquivalent(Mask, 1, 3))
8568     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8569
8570   if (Subtarget->hasSSE41())
8571     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8572                                                   Subtarget, DAG))
8573       return Blend;
8574
8575   // Try to use byte rotation instructions.
8576   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8577   if (Subtarget->hasSSSE3())
8578     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8579             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8580       return Rotate;
8581
8582   // We implement this with SHUFPD which is pretty lame because it will likely
8583   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8584   // However, all the alternatives are still more cycles and newer chips don't
8585   // have this problem. It would be really nice if x86 had better shuffles here.
8586   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
8587   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
8588   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
8589                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8590 }
8591
8592 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8593 ///
8594 /// This is used to disable more specialized lowerings when the shufps lowering
8595 /// will happen to be efficient.
8596 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8597   // This routine only handles 128-bit shufps.
8598   assert(Mask.size() == 4 && "Unsupported mask size!");
8599
8600   // To lower with a single SHUFPS we need to have the low half and high half
8601   // each requiring a single input.
8602   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8603     return false;
8604   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8605     return false;
8606
8607   return true;
8608 }
8609
8610 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8611 ///
8612 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8613 /// It makes no assumptions about whether this is the *best* lowering, it simply
8614 /// uses it.
8615 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8616                                             ArrayRef<int> Mask, SDValue V1,
8617                                             SDValue V2, SelectionDAG &DAG) {
8618   SDValue LowV = V1, HighV = V2;
8619   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8620
8621   int NumV2Elements =
8622       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8623
8624   if (NumV2Elements == 1) {
8625     int V2Index =
8626         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8627         Mask.begin();
8628
8629     // Compute the index adjacent to V2Index and in the same half by toggling
8630     // the low bit.
8631     int V2AdjIndex = V2Index ^ 1;
8632
8633     if (Mask[V2AdjIndex] == -1) {
8634       // Handles all the cases where we have a single V2 element and an undef.
8635       // This will only ever happen in the high lanes because we commute the
8636       // vector otherwise.
8637       if (V2Index < 2)
8638         std::swap(LowV, HighV);
8639       NewMask[V2Index] -= 4;
8640     } else {
8641       // Handle the case where the V2 element ends up adjacent to a V1 element.
8642       // To make this work, blend them together as the first step.
8643       int V1Index = V2AdjIndex;
8644       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8645       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8646                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8647
8648       // Now proceed to reconstruct the final blend as we have the necessary
8649       // high or low half formed.
8650       if (V2Index < 2) {
8651         LowV = V2;
8652         HighV = V1;
8653       } else {
8654         HighV = V2;
8655       }
8656       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8657       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8658     }
8659   } else if (NumV2Elements == 2) {
8660     if (Mask[0] < 4 && Mask[1] < 4) {
8661       // Handle the easy case where we have V1 in the low lanes and V2 in the
8662       // high lanes.
8663       NewMask[2] -= 4;
8664       NewMask[3] -= 4;
8665     } else if (Mask[2] < 4 && Mask[3] < 4) {
8666       // We also handle the reversed case because this utility may get called
8667       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8668       // arrange things in the right direction.
8669       NewMask[0] -= 4;
8670       NewMask[1] -= 4;
8671       HighV = V1;
8672       LowV = V2;
8673     } else {
8674       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8675       // trying to place elements directly, just blend them and set up the final
8676       // shuffle to place them.
8677
8678       // The first two blend mask elements are for V1, the second two are for
8679       // V2.
8680       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8681                           Mask[2] < 4 ? Mask[2] : Mask[3],
8682                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8683                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8684       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8685                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8686
8687       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8688       // a blend.
8689       LowV = HighV = V1;
8690       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8691       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8692       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8693       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8694     }
8695   }
8696   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8697                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
8698 }
8699
8700 /// \brief Lower 4-lane 32-bit floating point shuffles.
8701 ///
8702 /// Uses instructions exclusively from the floating point unit to minimize
8703 /// domain crossing penalties, as these are sufficient to implement all v4f32
8704 /// shuffles.
8705 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8706                                        const X86Subtarget *Subtarget,
8707                                        SelectionDAG &DAG) {
8708   SDLoc DL(Op);
8709   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8710   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8711   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8712   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8713   ArrayRef<int> Mask = SVOp->getMask();
8714   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8715
8716   int NumV2Elements =
8717       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8718
8719   if (NumV2Elements == 0) {
8720     // Check for being able to broadcast a single element.
8721     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
8722                                                           Mask, Subtarget, DAG))
8723       return Broadcast;
8724
8725     // Use even/odd duplicate instructions for masks that match their pattern.
8726     if (Subtarget->hasSSE3()) {
8727       if (isShuffleEquivalent(Mask, 0, 0, 2, 2))
8728         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8729       if (isShuffleEquivalent(Mask, 1, 1, 3, 3))
8730         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8731     }
8732
8733     if (Subtarget->hasAVX()) {
8734       // If we have AVX, we can use VPERMILPS which will allow folding a load
8735       // into the shuffle.
8736       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8737                          getV4X86ShuffleImm8ForMask(Mask, DAG));
8738     }
8739
8740     // Otherwise, use a straight shuffle of a single input vector. We pass the
8741     // input vector to both operands to simulate this with a SHUFPS.
8742     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8743                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8744   }
8745
8746   // Use dedicated unpack instructions for masks that match their pattern.
8747   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8748     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8749   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8750     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8751
8752   // There are special ways we can lower some single-element blends. However, we
8753   // have custom ways we can lower more complex single-element blends below that
8754   // we defer to if both this and BLENDPS fail to match, so restrict this to
8755   // when the V2 input is targeting element 0 of the mask -- that is the fast
8756   // case here.
8757   if (NumV2Elements == 1 && Mask[0] >= 4)
8758     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
8759                                                          Mask, Subtarget, DAG))
8760       return V;
8761
8762   if (Subtarget->hasSSE41()) {
8763     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8764                                                   Subtarget, DAG))
8765       return Blend;
8766
8767     // Use INSERTPS if we can complete the shuffle efficiently.
8768     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8769       return V;
8770
8771     if (!isSingleSHUFPSMask(Mask))
8772       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8773               DL, MVT::v4f32, V1, V2, Mask, DAG))
8774         return BlendPerm;
8775   }
8776
8777   // Otherwise fall back to a SHUFPS lowering strategy.
8778   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8779 }
8780
8781 /// \brief Lower 4-lane i32 vector shuffles.
8782 ///
8783 /// We try to handle these with integer-domain shuffles where we can, but for
8784 /// blends we use the floating point domain blend instructions.
8785 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8786                                        const X86Subtarget *Subtarget,
8787                                        SelectionDAG &DAG) {
8788   SDLoc DL(Op);
8789   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8790   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8791   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8792   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8793   ArrayRef<int> Mask = SVOp->getMask();
8794   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8795
8796   // Whenever we can lower this as a zext, that instruction is strictly faster
8797   // than any alternative. It also allows us to fold memory operands into the
8798   // shuffle in many cases.
8799   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8800                                                          Mask, Subtarget, DAG))
8801     return ZExt;
8802
8803   int NumV2Elements =
8804       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8805
8806   if (NumV2Elements == 0) {
8807     // Check for being able to broadcast a single element.
8808     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
8809                                                           Mask, Subtarget, DAG))
8810       return Broadcast;
8811
8812     // Straight shuffle of a single input vector. For everything from SSE2
8813     // onward this has a single fast instruction with no scary immediates.
8814     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8815     // but we aren't actually going to use the UNPCK instruction because doing
8816     // so prevents folding a load into this instruction or making a copy.
8817     const int UnpackLoMask[] = {0, 0, 1, 1};
8818     const int UnpackHiMask[] = {2, 2, 3, 3};
8819     if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
8820       Mask = UnpackLoMask;
8821     else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
8822       Mask = UnpackHiMask;
8823
8824     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8825                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8826   }
8827
8828   // Try to use bit shift instructions.
8829   if (SDValue Shift = lowerVectorShuffleAsBitShift(
8830           DL, MVT::v4i32, V1, V2, Mask, DAG))
8831     return Shift;
8832
8833   // Try to use byte shift instructions.
8834   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8835           DL, MVT::v4i32, V1, V2, Mask, DAG))
8836     return Shift;
8837
8838   // There are special ways we can lower some single-element blends.
8839   if (NumV2Elements == 1)
8840     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
8841                                                          Mask, Subtarget, DAG))
8842       return V;
8843
8844   if (Subtarget->hasSSE41())
8845     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8846                                                   Subtarget, DAG))
8847       return Blend;
8848
8849   if (SDValue Masked =
8850           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8851     return Masked;
8852
8853   // Use dedicated unpack instructions for masks that match their pattern.
8854   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8855     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8856   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8857     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8858
8859   // Try to use byte rotation instructions.
8860   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8861   if (Subtarget->hasSSSE3())
8862     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8863             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8864       return Rotate;
8865
8866   // We implement this with SHUFPS because it can blend from two vectors.
8867   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8868   // up the inputs, bypassing domain shift penalties that we would encur if we
8869   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8870   // relevant.
8871   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
8872                      DAG.getVectorShuffle(
8873                          MVT::v4f32, DL,
8874                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
8875                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
8876 }
8877
8878 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8879 /// shuffle lowering, and the most complex part.
8880 ///
8881 /// The lowering strategy is to try to form pairs of input lanes which are
8882 /// targeted at the same half of the final vector, and then use a dword shuffle
8883 /// to place them onto the right half, and finally unpack the paired lanes into
8884 /// their final position.
8885 ///
8886 /// The exact breakdown of how to form these dword pairs and align them on the
8887 /// correct sides is really tricky. See the comments within the function for
8888 /// more of the details.
8889 static SDValue lowerV8I16SingleInputVectorShuffle(
8890     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
8891     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8892   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8893   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8894   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8895
8896   SmallVector<int, 4> LoInputs;
8897   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8898                [](int M) { return M >= 0; });
8899   std::sort(LoInputs.begin(), LoInputs.end());
8900   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8901   SmallVector<int, 4> HiInputs;
8902   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8903                [](int M) { return M >= 0; });
8904   std::sort(HiInputs.begin(), HiInputs.end());
8905   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8906   int NumLToL =
8907       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8908   int NumHToL = LoInputs.size() - NumLToL;
8909   int NumLToH =
8910       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8911   int NumHToH = HiInputs.size() - NumLToH;
8912   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8913   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8914   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8915   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8916
8917   // Check for being able to broadcast a single element.
8918   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
8919                                                         Mask, Subtarget, DAG))
8920     return Broadcast;
8921
8922   // Try to use bit shift instructions.
8923   if (SDValue Shift = lowerVectorShuffleAsBitShift(
8924           DL, MVT::v8i16, V, V, Mask, DAG))
8925     return Shift;
8926
8927   // Try to use byte shift instructions.
8928   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8929           DL, MVT::v8i16, V, V, Mask, DAG))
8930     return Shift;
8931
8932   // Use dedicated unpack instructions for masks that match their pattern.
8933   if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
8934     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
8935   if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
8936     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
8937
8938   // Try to use byte rotation instructions.
8939   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8940           DL, MVT::v8i16, V, V, Mask, Subtarget, DAG))
8941     return Rotate;
8942
8943   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8944   // such inputs we can swap two of the dwords across the half mark and end up
8945   // with <=2 inputs to each half in each half. Once there, we can fall through
8946   // to the generic code below. For example:
8947   //
8948   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8949   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8950   //
8951   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8952   // and an existing 2-into-2 on the other half. In this case we may have to
8953   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8954   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8955   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8956   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8957   // half than the one we target for fixing) will be fixed when we re-enter this
8958   // path. We will also combine away any sequence of PSHUFD instructions that
8959   // result into a single instruction. Here is an example of the tricky case:
8960   //
8961   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8962   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8963   //
8964   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8965   //
8966   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8967   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8968   //
8969   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8970   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8971   //
8972   // The result is fine to be handled by the generic logic.
8973   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8974                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8975                           int AOffset, int BOffset) {
8976     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8977            "Must call this with A having 3 or 1 inputs from the A half.");
8978     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8979            "Must call this with B having 1 or 3 inputs from the B half.");
8980     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8981            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8982
8983     // Compute the index of dword with only one word among the three inputs in
8984     // a half by taking the sum of the half with three inputs and subtracting
8985     // the sum of the actual three inputs. The difference is the remaining
8986     // slot.
8987     int ADWord, BDWord;
8988     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8989     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8990     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8991     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8992     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8993     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8994     int TripleNonInputIdx =
8995         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8996     TripleDWord = TripleNonInputIdx / 2;
8997
8998     // We use xor with one to compute the adjacent DWord to whichever one the
8999     // OneInput is in.
9000     OneInputDWord = (OneInput / 2) ^ 1;
9001
9002     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
9003     // and BToA inputs. If there is also such a problem with the BToB and AToB
9004     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
9005     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9006     // is essential that we don't *create* a 3<-1 as then we might oscillate.
9007     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9008       // Compute how many inputs will be flipped by swapping these DWords. We
9009       // need
9010       // to balance this to ensure we don't form a 3-1 shuffle in the other
9011       // half.
9012       int NumFlippedAToBInputs =
9013           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9014           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9015       int NumFlippedBToBInputs =
9016           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9017           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9018       if ((NumFlippedAToBInputs == 1 &&
9019            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9020           (NumFlippedBToBInputs == 1 &&
9021            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9022         // We choose whether to fix the A half or B half based on whether that
9023         // half has zero flipped inputs. At zero, we may not be able to fix it
9024         // with that half. We also bias towards fixing the B half because that
9025         // will more commonly be the high half, and we have to bias one way.
9026         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9027                                                        ArrayRef<int> Inputs) {
9028           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9029           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9030                                          PinnedIdx ^ 1) != Inputs.end();
9031           // Determine whether the free index is in the flipped dword or the
9032           // unflipped dword based on where the pinned index is. We use this bit
9033           // in an xor to conditionally select the adjacent dword.
9034           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9035           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9036                                              FixFreeIdx) != Inputs.end();
9037           if (IsFixIdxInput == IsFixFreeIdxInput)
9038             FixFreeIdx += 1;
9039           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9040                                         FixFreeIdx) != Inputs.end();
9041           assert(IsFixIdxInput != IsFixFreeIdxInput &&
9042                  "We need to be changing the number of flipped inputs!");
9043           int PSHUFHalfMask[] = {0, 1, 2, 3};
9044           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9045           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9046                           MVT::v8i16, V,
9047                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
9048
9049           for (int &M : Mask)
9050             if (M != -1 && M == FixIdx)
9051               M = FixFreeIdx;
9052             else if (M != -1 && M == FixFreeIdx)
9053               M = FixIdx;
9054         };
9055         if (NumFlippedBToBInputs != 0) {
9056           int BPinnedIdx =
9057               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9058           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9059         } else {
9060           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9061           int APinnedIdx =
9062               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9063           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9064         }
9065       }
9066     }
9067
9068     int PSHUFDMask[] = {0, 1, 2, 3};
9069     PSHUFDMask[ADWord] = BDWord;
9070     PSHUFDMask[BDWord] = ADWord;
9071     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9072                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
9073                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
9074                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9075
9076     // Adjust the mask to match the new locations of A and B.
9077     for (int &M : Mask)
9078       if (M != -1 && M/2 == ADWord)
9079         M = 2 * BDWord + M % 2;
9080       else if (M != -1 && M/2 == BDWord)
9081         M = 2 * ADWord + M % 2;
9082
9083     // Recurse back into this routine to re-compute state now that this isn't
9084     // a 3 and 1 problem.
9085     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
9086                                 Mask);
9087   };
9088   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9089     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9090   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9091     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9092
9093   // At this point there are at most two inputs to the low and high halves from
9094   // each half. That means the inputs can always be grouped into dwords and
9095   // those dwords can then be moved to the correct half with a dword shuffle.
9096   // We use at most one low and one high word shuffle to collect these paired
9097   // inputs into dwords, and finally a dword shuffle to place them.
9098   int PSHUFLMask[4] = {-1, -1, -1, -1};
9099   int PSHUFHMask[4] = {-1, -1, -1, -1};
9100   int PSHUFDMask[4] = {-1, -1, -1, -1};
9101
9102   // First fix the masks for all the inputs that are staying in their
9103   // original halves. This will then dictate the targets of the cross-half
9104   // shuffles.
9105   auto fixInPlaceInputs =
9106       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9107                     MutableArrayRef<int> SourceHalfMask,
9108                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9109     if (InPlaceInputs.empty())
9110       return;
9111     if (InPlaceInputs.size() == 1) {
9112       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9113           InPlaceInputs[0] - HalfOffset;
9114       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9115       return;
9116     }
9117     if (IncomingInputs.empty()) {
9118       // Just fix all of the in place inputs.
9119       for (int Input : InPlaceInputs) {
9120         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9121         PSHUFDMask[Input / 2] = Input / 2;
9122       }
9123       return;
9124     }
9125
9126     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9127     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9128         InPlaceInputs[0] - HalfOffset;
9129     // Put the second input next to the first so that they are packed into
9130     // a dword. We find the adjacent index by toggling the low bit.
9131     int AdjIndex = InPlaceInputs[0] ^ 1;
9132     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9133     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9134     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9135   };
9136   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9137   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9138
9139   // Now gather the cross-half inputs and place them into a free dword of
9140   // their target half.
9141   // FIXME: This operation could almost certainly be simplified dramatically to
9142   // look more like the 3-1 fixing operation.
9143   auto moveInputsToRightHalf = [&PSHUFDMask](
9144       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9145       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9146       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9147       int DestOffset) {
9148     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9149       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9150     };
9151     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9152                                                int Word) {
9153       int LowWord = Word & ~1;
9154       int HighWord = Word | 1;
9155       return isWordClobbered(SourceHalfMask, LowWord) ||
9156              isWordClobbered(SourceHalfMask, HighWord);
9157     };
9158
9159     if (IncomingInputs.empty())
9160       return;
9161
9162     if (ExistingInputs.empty()) {
9163       // Map any dwords with inputs from them into the right half.
9164       for (int Input : IncomingInputs) {
9165         // If the source half mask maps over the inputs, turn those into
9166         // swaps and use the swapped lane.
9167         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9168           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9169             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9170                 Input - SourceOffset;
9171             // We have to swap the uses in our half mask in one sweep.
9172             for (int &M : HalfMask)
9173               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9174                 M = Input;
9175               else if (M == Input)
9176                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9177           } else {
9178             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9179                        Input - SourceOffset &&
9180                    "Previous placement doesn't match!");
9181           }
9182           // Note that this correctly re-maps both when we do a swap and when
9183           // we observe the other side of the swap above. We rely on that to
9184           // avoid swapping the members of the input list directly.
9185           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9186         }
9187
9188         // Map the input's dword into the correct half.
9189         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9190           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9191         else
9192           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9193                      Input / 2 &&
9194                  "Previous placement doesn't match!");
9195       }
9196
9197       // And just directly shift any other-half mask elements to be same-half
9198       // as we will have mirrored the dword containing the element into the
9199       // same position within that half.
9200       for (int &M : HalfMask)
9201         if (M >= SourceOffset && M < SourceOffset + 4) {
9202           M = M - SourceOffset + DestOffset;
9203           assert(M >= 0 && "This should never wrap below zero!");
9204         }
9205       return;
9206     }
9207
9208     // Ensure we have the input in a viable dword of its current half. This
9209     // is particularly tricky because the original position may be clobbered
9210     // by inputs being moved and *staying* in that half.
9211     if (IncomingInputs.size() == 1) {
9212       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9213         int InputFixed = std::find(std::begin(SourceHalfMask),
9214                                    std::end(SourceHalfMask), -1) -
9215                          std::begin(SourceHalfMask) + SourceOffset;
9216         SourceHalfMask[InputFixed - SourceOffset] =
9217             IncomingInputs[0] - SourceOffset;
9218         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9219                      InputFixed);
9220         IncomingInputs[0] = InputFixed;
9221       }
9222     } else if (IncomingInputs.size() == 2) {
9223       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9224           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9225         // We have two non-adjacent or clobbered inputs we need to extract from
9226         // the source half. To do this, we need to map them into some adjacent
9227         // dword slot in the source mask.
9228         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9229                               IncomingInputs[1] - SourceOffset};
9230
9231         // If there is a free slot in the source half mask adjacent to one of
9232         // the inputs, place the other input in it. We use (Index XOR 1) to
9233         // compute an adjacent index.
9234         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9235             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9236           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9237           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9238           InputsFixed[1] = InputsFixed[0] ^ 1;
9239         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9240                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9241           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9242           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9243           InputsFixed[0] = InputsFixed[1] ^ 1;
9244         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9245                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9246           // The two inputs are in the same DWord but it is clobbered and the
9247           // adjacent DWord isn't used at all. Move both inputs to the free
9248           // slot.
9249           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9250           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9251           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9252           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9253         } else {
9254           // The only way we hit this point is if there is no clobbering
9255           // (because there are no off-half inputs to this half) and there is no
9256           // free slot adjacent to one of the inputs. In this case, we have to
9257           // swap an input with a non-input.
9258           for (int i = 0; i < 4; ++i)
9259             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9260                    "We can't handle any clobbers here!");
9261           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9262                  "Cannot have adjacent inputs here!");
9263
9264           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9265           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9266
9267           // We also have to update the final source mask in this case because
9268           // it may need to undo the above swap.
9269           for (int &M : FinalSourceHalfMask)
9270             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9271               M = InputsFixed[1] + SourceOffset;
9272             else if (M == InputsFixed[1] + SourceOffset)
9273               M = (InputsFixed[0] ^ 1) + SourceOffset;
9274
9275           InputsFixed[1] = InputsFixed[0] ^ 1;
9276         }
9277
9278         // Point everything at the fixed inputs.
9279         for (int &M : HalfMask)
9280           if (M == IncomingInputs[0])
9281             M = InputsFixed[0] + SourceOffset;
9282           else if (M == IncomingInputs[1])
9283             M = InputsFixed[1] + SourceOffset;
9284
9285         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9286         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9287       }
9288     } else {
9289       llvm_unreachable("Unhandled input size!");
9290     }
9291
9292     // Now hoist the DWord down to the right half.
9293     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9294     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9295     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9296     for (int &M : HalfMask)
9297       for (int Input : IncomingInputs)
9298         if (M == Input)
9299           M = FreeDWord * 2 + Input % 2;
9300   };
9301   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9302                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9303   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9304                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9305
9306   // Now enact all the shuffles we've computed to move the inputs into their
9307   // target half.
9308   if (!isNoopShuffleMask(PSHUFLMask))
9309     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
9310                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
9311   if (!isNoopShuffleMask(PSHUFHMask))
9312     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
9313                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
9314   if (!isNoopShuffleMask(PSHUFDMask))
9315     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9316                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
9317                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
9318                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9319
9320   // At this point, each half should contain all its inputs, and we can then
9321   // just shuffle them into their final position.
9322   assert(std::count_if(LoMask.begin(), LoMask.end(),
9323                        [](int M) { return M >= 4; }) == 0 &&
9324          "Failed to lift all the high half inputs to the low mask!");
9325   assert(std::count_if(HiMask.begin(), HiMask.end(),
9326                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9327          "Failed to lift all the low half inputs to the high mask!");
9328
9329   // Do a half shuffle for the low mask.
9330   if (!isNoopShuffleMask(LoMask))
9331     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
9332                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
9333
9334   // Do a half shuffle with the high mask after shifting its values down.
9335   for (int &M : HiMask)
9336     if (M >= 0)
9337       M -= 4;
9338   if (!isNoopShuffleMask(HiMask))
9339     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
9340                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
9341
9342   return V;
9343 }
9344
9345 /// \brief Detect whether the mask pattern should be lowered through
9346 /// interleaving.
9347 ///
9348 /// This essentially tests whether viewing the mask as an interleaving of two
9349 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
9350 /// lowering it through interleaving is a significantly better strategy.
9351 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
9352   int NumEvenInputs[2] = {0, 0};
9353   int NumOddInputs[2] = {0, 0};
9354   int NumLoInputs[2] = {0, 0};
9355   int NumHiInputs[2] = {0, 0};
9356   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9357     if (Mask[i] < 0)
9358       continue;
9359
9360     int InputIdx = Mask[i] >= Size;
9361
9362     if (i < Size / 2)
9363       ++NumLoInputs[InputIdx];
9364     else
9365       ++NumHiInputs[InputIdx];
9366
9367     if ((i % 2) == 0)
9368       ++NumEvenInputs[InputIdx];
9369     else
9370       ++NumOddInputs[InputIdx];
9371   }
9372
9373   // The minimum number of cross-input results for both the interleaved and
9374   // split cases. If interleaving results in fewer cross-input results, return
9375   // true.
9376   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
9377                                     NumEvenInputs[0] + NumOddInputs[1]);
9378   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
9379                               NumLoInputs[0] + NumHiInputs[1]);
9380   return InterleavedCrosses < SplitCrosses;
9381 }
9382
9383 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
9384 ///
9385 /// This strategy only works when the inputs from each vector fit into a single
9386 /// half of that vector, and generally there are not so many inputs as to leave
9387 /// the in-place shuffles required highly constrained (and thus expensive). It
9388 /// shifts all the inputs into a single side of both input vectors and then
9389 /// uses an unpack to interleave these inputs in a single vector. At that
9390 /// point, we will fall back on the generic single input shuffle lowering.
9391 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
9392                                                  SDValue V2,
9393                                                  MutableArrayRef<int> Mask,
9394                                                  const X86Subtarget *Subtarget,
9395                                                  SelectionDAG &DAG) {
9396   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9397   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9398   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
9399   for (int i = 0; i < 8; ++i)
9400     if (Mask[i] >= 0 && Mask[i] < 4)
9401       LoV1Inputs.push_back(i);
9402     else if (Mask[i] >= 4 && Mask[i] < 8)
9403       HiV1Inputs.push_back(i);
9404     else if (Mask[i] >= 8 && Mask[i] < 12)
9405       LoV2Inputs.push_back(i);
9406     else if (Mask[i] >= 12)
9407       HiV2Inputs.push_back(i);
9408
9409   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
9410   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
9411   (void)NumV1Inputs;
9412   (void)NumV2Inputs;
9413   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
9414   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
9415   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
9416
9417   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
9418                      HiV1Inputs.size() + HiV2Inputs.size();
9419
9420   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
9421                               ArrayRef<int> HiInputs, bool MoveToLo,
9422                               int MaskOffset) {
9423     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
9424     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
9425     if (BadInputs.empty())
9426       return V;
9427
9428     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9429     int MoveOffset = MoveToLo ? 0 : 4;
9430
9431     if (GoodInputs.empty()) {
9432       for (int BadInput : BadInputs) {
9433         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
9434         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
9435       }
9436     } else {
9437       if (GoodInputs.size() == 2) {
9438         // If the low inputs are spread across two dwords, pack them into
9439         // a single dword.
9440         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
9441         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
9442         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
9443         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
9444       } else {
9445         // Otherwise pin the good inputs.
9446         for (int GoodInput : GoodInputs)
9447           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
9448       }
9449
9450       if (BadInputs.size() == 2) {
9451         // If we have two bad inputs then there may be either one or two good
9452         // inputs fixed in place. Find a fixed input, and then find the *other*
9453         // two adjacent indices by using modular arithmetic.
9454         int GoodMaskIdx =
9455             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
9456                          [](int M) { return M >= 0; }) -
9457             std::begin(MoveMask);
9458         int MoveMaskIdx =
9459             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
9460         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
9461         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
9462         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9463         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
9464         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9465         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
9466       } else {
9467         assert(BadInputs.size() == 1 && "All sizes handled");
9468         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
9469                                     std::end(MoveMask), -1) -
9470                           std::begin(MoveMask);
9471         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9472         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9473       }
9474     }
9475
9476     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
9477                                 MoveMask);
9478   };
9479   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
9480                         /*MaskOffset*/ 0);
9481   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
9482                         /*MaskOffset*/ 8);
9483
9484   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
9485   // cross-half traffic in the final shuffle.
9486
9487   // Munge the mask to be a single-input mask after the unpack merges the
9488   // results.
9489   for (int &M : Mask)
9490     if (M != -1)
9491       M = 2 * (M % 4) + (M / 8);
9492
9493   return DAG.getVectorShuffle(
9494       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
9495                                   DL, MVT::v8i16, V1, V2),
9496       DAG.getUNDEF(MVT::v8i16), Mask);
9497 }
9498
9499 /// \brief Generic lowering of 8-lane i16 shuffles.
9500 ///
9501 /// This handles both single-input shuffles and combined shuffle/blends with
9502 /// two inputs. The single input shuffles are immediately delegated to
9503 /// a dedicated lowering routine.
9504 ///
9505 /// The blends are lowered in one of three fundamental ways. If there are few
9506 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9507 /// of the input is significantly cheaper when lowered as an interleaving of
9508 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9509 /// halves of the inputs separately (making them have relatively few inputs)
9510 /// and then concatenate them.
9511 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9512                                        const X86Subtarget *Subtarget,
9513                                        SelectionDAG &DAG) {
9514   SDLoc DL(Op);
9515   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9516   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9517   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9518   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9519   ArrayRef<int> OrigMask = SVOp->getMask();
9520   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9521                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9522   MutableArrayRef<int> Mask(MaskStorage);
9523
9524   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9525
9526   // Whenever we can lower this as a zext, that instruction is strictly faster
9527   // than any alternative.
9528   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9529           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9530     return ZExt;
9531
9532   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9533   auto isV2 = [](int M) { return M >= 8; };
9534
9535   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
9536   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9537
9538   if (NumV2Inputs == 0)
9539     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
9540
9541   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
9542                             "to be V1-input shuffles.");
9543
9544   // Try to use bit shift instructions.
9545   if (SDValue Shift = lowerVectorShuffleAsBitShift(
9546           DL, MVT::v8i16, V1, V2, Mask, DAG))
9547     return Shift;
9548
9549   // Try to use byte shift instructions.
9550   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9551           DL, MVT::v8i16, V1, V2, Mask, DAG))
9552     return Shift;
9553
9554   // There are special ways we can lower some single-element blends.
9555   if (NumV2Inputs == 1)
9556     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
9557                                                          Mask, Subtarget, DAG))
9558       return V;
9559
9560   if (Subtarget->hasSSE41())
9561     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9562                                                   Subtarget, DAG))
9563       return Blend;
9564
9565   if (SDValue Masked =
9566           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9567     return Masked;
9568
9569   // Use dedicated unpack instructions for masks that match their pattern.
9570   if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 2, 10, 3, 11))
9571     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9572   if (isShuffleEquivalent(Mask, 4, 12, 5, 13, 6, 14, 7, 15))
9573     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9574
9575   // Try to use byte rotation instructions.
9576   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9577           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9578     return Rotate;
9579
9580   if (NumV1Inputs + NumV2Inputs <= 4)
9581     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
9582
9583   // Check whether an interleaving lowering is likely to be more efficient.
9584   // This isn't perfect but it is a strong heuristic that tends to work well on
9585   // the kinds of shuffles that show up in practice.
9586   //
9587   // FIXME: Handle 1x, 2x, and 4x interleaving.
9588   if (shouldLowerAsInterleaving(Mask)) {
9589     // FIXME: Figure out whether we should pack these into the low or high
9590     // halves.
9591
9592     int EMask[8], OMask[8];
9593     for (int i = 0; i < 4; ++i) {
9594       EMask[i] = Mask[2*i];
9595       OMask[i] = Mask[2*i + 1];
9596       EMask[i + 4] = -1;
9597       OMask[i + 4] = -1;
9598     }
9599
9600     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
9601     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
9602
9603     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
9604   }
9605
9606   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9607   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9608
9609   for (int i = 0; i < 4; ++i) {
9610     LoBlendMask[i] = Mask[i];
9611     HiBlendMask[i] = Mask[i + 4];
9612   }
9613
9614   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9615   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9616   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
9617   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
9618
9619   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9620                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
9621 }
9622
9623 /// \brief Check whether a compaction lowering can be done by dropping even
9624 /// elements and compute how many times even elements must be dropped.
9625 ///
9626 /// This handles shuffles which take every Nth element where N is a power of
9627 /// two. Example shuffle masks:
9628 ///
9629 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9630 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9631 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9632 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9633 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9634 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9635 ///
9636 /// Any of these lanes can of course be undef.
9637 ///
9638 /// This routine only supports N <= 3.
9639 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9640 /// for larger N.
9641 ///
9642 /// \returns N above, or the number of times even elements must be dropped if
9643 /// there is such a number. Otherwise returns zero.
9644 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9645   // Figure out whether we're looping over two inputs or just one.
9646   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9647
9648   // The modulus for the shuffle vector entries is based on whether this is
9649   // a single input or not.
9650   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9651   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9652          "We should only be called with masks with a power-of-2 size!");
9653
9654   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9655
9656   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9657   // and 2^3 simultaneously. This is because we may have ambiguity with
9658   // partially undef inputs.
9659   bool ViableForN[3] = {true, true, true};
9660
9661   for (int i = 0, e = Mask.size(); i < e; ++i) {
9662     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9663     // want.
9664     if (Mask[i] == -1)
9665       continue;
9666
9667     bool IsAnyViable = false;
9668     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9669       if (ViableForN[j]) {
9670         uint64_t N = j + 1;
9671
9672         // The shuffle mask must be equal to (i * 2^N) % M.
9673         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9674           IsAnyViable = true;
9675         else
9676           ViableForN[j] = false;
9677       }
9678     // Early exit if we exhaust the possible powers of two.
9679     if (!IsAnyViable)
9680       break;
9681   }
9682
9683   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9684     if (ViableForN[j])
9685       return j + 1;
9686
9687   // Return 0 as there is no viable power of two.
9688   return 0;
9689 }
9690
9691 /// \brief Generic lowering of v16i8 shuffles.
9692 ///
9693 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9694 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9695 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9696 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9697 /// back together.
9698 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9699                                        const X86Subtarget *Subtarget,
9700                                        SelectionDAG &DAG) {
9701   SDLoc DL(Op);
9702   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9703   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9704   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9705   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9706   ArrayRef<int> OrigMask = SVOp->getMask();
9707   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9708
9709   // Try to use bit shift instructions.
9710   if (SDValue Shift = lowerVectorShuffleAsBitShift(
9711           DL, MVT::v16i8, V1, V2, OrigMask, DAG))
9712     return Shift;
9713
9714   // Try to use byte shift instructions.
9715   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9716           DL, MVT::v16i8, V1, V2, OrigMask, DAG))
9717     return Shift;
9718
9719   // Try to use byte rotation instructions.
9720   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9721           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9722     return Rotate;
9723
9724   // Try to use a zext lowering.
9725   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9726           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9727     return ZExt;
9728
9729   int MaskStorage[16] = {
9730       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
9731       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
9732       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
9733       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
9734   MutableArrayRef<int> Mask(MaskStorage);
9735   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
9736   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
9737
9738   int NumV2Elements =
9739       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9740
9741   // For single-input shuffles, there are some nicer lowering tricks we can use.
9742   if (NumV2Elements == 0) {
9743     // Check for being able to broadcast a single element.
9744     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
9745                                                           Mask, Subtarget, DAG))
9746       return Broadcast;
9747
9748     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9749     // Notably, this handles splat and partial-splat shuffles more efficiently.
9750     // However, it only makes sense if the pre-duplication shuffle simplifies
9751     // things significantly. Currently, this means we need to be able to
9752     // express the pre-duplication shuffle as an i16 shuffle.
9753     //
9754     // FIXME: We should check for other patterns which can be widened into an
9755     // i16 shuffle as well.
9756     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9757       for (int i = 0; i < 16; i += 2)
9758         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9759           return false;
9760
9761       return true;
9762     };
9763     auto tryToWidenViaDuplication = [&]() -> SDValue {
9764       if (!canWidenViaDuplication(Mask))
9765         return SDValue();
9766       SmallVector<int, 4> LoInputs;
9767       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9768                    [](int M) { return M >= 0 && M < 8; });
9769       std::sort(LoInputs.begin(), LoInputs.end());
9770       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9771                      LoInputs.end());
9772       SmallVector<int, 4> HiInputs;
9773       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9774                    [](int M) { return M >= 8; });
9775       std::sort(HiInputs.begin(), HiInputs.end());
9776       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9777                      HiInputs.end());
9778
9779       bool TargetLo = LoInputs.size() >= HiInputs.size();
9780       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9781       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9782
9783       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9784       SmallDenseMap<int, int, 8> LaneMap;
9785       for (int I : InPlaceInputs) {
9786         PreDupI16Shuffle[I/2] = I/2;
9787         LaneMap[I] = I;
9788       }
9789       int j = TargetLo ? 0 : 4, je = j + 4;
9790       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9791         // Check if j is already a shuffle of this input. This happens when
9792         // there are two adjacent bytes after we move the low one.
9793         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9794           // If we haven't yet mapped the input, search for a slot into which
9795           // we can map it.
9796           while (j < je && PreDupI16Shuffle[j] != -1)
9797             ++j;
9798
9799           if (j == je)
9800             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9801             return SDValue();
9802
9803           // Map this input with the i16 shuffle.
9804           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9805         }
9806
9807         // Update the lane map based on the mapping we ended up with.
9808         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9809       }
9810       V1 = DAG.getNode(
9811           ISD::BITCAST, DL, MVT::v16i8,
9812           DAG.getVectorShuffle(MVT::v8i16, DL,
9813                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9814                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9815
9816       // Unpack the bytes to form the i16s that will be shuffled into place.
9817       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9818                        MVT::v16i8, V1, V1);
9819
9820       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9821       for (int i = 0; i < 16; ++i)
9822         if (Mask[i] != -1) {
9823           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9824           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9825           if (PostDupI16Shuffle[i / 2] == -1)
9826             PostDupI16Shuffle[i / 2] = MappedMask;
9827           else
9828             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9829                    "Conflicting entrties in the original shuffle!");
9830         }
9831       return DAG.getNode(
9832           ISD::BITCAST, DL, MVT::v16i8,
9833           DAG.getVectorShuffle(MVT::v8i16, DL,
9834                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9835                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9836     };
9837     if (SDValue V = tryToWidenViaDuplication())
9838       return V;
9839   }
9840
9841   // Check whether an interleaving lowering is likely to be more efficient.
9842   // This isn't perfect but it is a strong heuristic that tends to work well on
9843   // the kinds of shuffles that show up in practice.
9844   //
9845   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
9846   if (shouldLowerAsInterleaving(Mask)) {
9847     int NumLoHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9848       return (M >= 0 && M < 8) || (M >= 16 && M < 24);
9849     });
9850     int NumHiHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9851       return (M >= 8 && M < 16) || M >= 24;
9852     });
9853     int EMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9854                      -1, -1, -1, -1, -1, -1, -1, -1};
9855     int OMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9856                      -1, -1, -1, -1, -1, -1, -1, -1};
9857     bool UnpackLo = NumLoHalf >= NumHiHalf;
9858     MutableArrayRef<int> TargetEMask(UnpackLo ? EMask : EMask + 8, 8);
9859     MutableArrayRef<int> TargetOMask(UnpackLo ? OMask : OMask + 8, 8);
9860     for (int i = 0; i < 8; ++i) {
9861       TargetEMask[i] = Mask[2 * i];
9862       TargetOMask[i] = Mask[2 * i + 1];
9863     }
9864
9865     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
9866     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
9867
9868     return DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9869                        MVT::v16i8, Evens, Odds);
9870   }
9871
9872   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9873   // with PSHUFB. It is important to do this before we attempt to generate any
9874   // blends but after all of the single-input lowerings. If the single input
9875   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9876   // want to preserve that and we can DAG combine any longer sequences into
9877   // a PSHUFB in the end. But once we start blending from multiple inputs,
9878   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9879   // and there are *very* few patterns that would actually be faster than the
9880   // PSHUFB approach because of its ability to zero lanes.
9881   //
9882   // FIXME: The only exceptions to the above are blends which are exact
9883   // interleavings with direct instructions supporting them. We currently don't
9884   // handle those well here.
9885   if (Subtarget->hasSSSE3()) {
9886     SDValue V1Mask[16];
9887     SDValue V2Mask[16];
9888     bool V1InUse = false;
9889     bool V2InUse = false;
9890     SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9891
9892     for (int i = 0; i < 16; ++i) {
9893       if (Mask[i] == -1) {
9894         V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9895       } else {
9896         const int ZeroMask = 0x80;
9897         int V1Idx = (Mask[i] < 16 ? Mask[i] : ZeroMask);
9898         int V2Idx = (Mask[i] < 16 ? ZeroMask : Mask[i] - 16);
9899         if (Zeroable[i])
9900           V1Idx = V2Idx = ZeroMask;
9901         V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
9902         V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
9903         V1InUse |= (ZeroMask != V1Idx);
9904         V2InUse |= (ZeroMask != V2Idx);
9905       }
9906     }
9907
9908     if (V1InUse)
9909       V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
9910                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9911     if (V2InUse)
9912       V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
9913                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9914
9915     // If we need shuffled inputs from both, blend the two.
9916     if (V1InUse && V2InUse)
9917       return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9918     if (V1InUse)
9919       return V1; // Single inputs are easy.
9920     if (V2InUse)
9921       return V2; // Single inputs are easy.
9922     // Shuffling to a zeroable vector.
9923     return getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
9924   }
9925
9926   // There are special ways we can lower some single-element blends.
9927   if (NumV2Elements == 1)
9928     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
9929                                                          Mask, Subtarget, DAG))
9930       return V;
9931
9932   // Check whether a compaction lowering can be done. This handles shuffles
9933   // which take every Nth element for some even N. See the helper function for
9934   // details.
9935   //
9936   // We special case these as they can be particularly efficiently handled with
9937   // the PACKUSB instruction on x86 and they show up in common patterns of
9938   // rearranging bytes to truncate wide elements.
9939   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9940     // NumEvenDrops is the power of two stride of the elements. Another way of
9941     // thinking about it is that we need to drop the even elements this many
9942     // times to get the original input.
9943     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9944
9945     // First we need to zero all the dropped bytes.
9946     assert(NumEvenDrops <= 3 &&
9947            "No support for dropping even elements more than 3 times.");
9948     // We use the mask type to pick which bytes are preserved based on how many
9949     // elements are dropped.
9950     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9951     SDValue ByteClearMask =
9952         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
9953                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
9954     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9955     if (!IsSingleInput)
9956       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9957
9958     // Now pack things back together.
9959     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
9960     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
9961     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9962     for (int i = 1; i < NumEvenDrops; ++i) {
9963       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
9964       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9965     }
9966
9967     return Result;
9968   }
9969
9970   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9971   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9972   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9973   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9974
9975   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
9976                             MutableArrayRef<int> V1HalfBlendMask,
9977                             MutableArrayRef<int> V2HalfBlendMask) {
9978     for (int i = 0; i < 8; ++i)
9979       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
9980         V1HalfBlendMask[i] = HalfMask[i];
9981         HalfMask[i] = i;
9982       } else if (HalfMask[i] >= 16) {
9983         V2HalfBlendMask[i] = HalfMask[i] - 16;
9984         HalfMask[i] = i + 8;
9985       }
9986   };
9987   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
9988   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
9989
9990   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9991
9992   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
9993                              MutableArrayRef<int> HiBlendMask) {
9994     SDValue V1, V2;
9995     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9996     // them out and avoid using UNPCK{L,H} to extract the elements of V as
9997     // i16s.
9998     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
9999                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
10000         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
10001                      [](int M) { return M >= 0 && M % 2 == 1; })) {
10002       // Use a mask to drop the high bytes.
10003       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
10004       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
10005                        DAG.getConstant(0x00FF, MVT::v8i16));
10006
10007       // This will be a single vector shuffle instead of a blend so nuke V2.
10008       V2 = DAG.getUNDEF(MVT::v8i16);
10009
10010       // Squash the masks to point directly into V1.
10011       for (int &M : LoBlendMask)
10012         if (M >= 0)
10013           M /= 2;
10014       for (int &M : HiBlendMask)
10015         if (M >= 0)
10016           M /= 2;
10017     } else {
10018       // Otherwise just unpack the low half of V into V1 and the high half into
10019       // V2 so that we can blend them as i16s.
10020       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
10021                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
10022       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
10023                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
10024     }
10025
10026     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
10027     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
10028     return std::make_pair(BlendedLo, BlendedHi);
10029   };
10030   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
10031   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
10032   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
10033
10034   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
10035   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
10036
10037   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
10038 }
10039
10040 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
10041 ///
10042 /// This routine breaks down the specific type of 128-bit shuffle and
10043 /// dispatches to the lowering routines accordingly.
10044 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10045                                         MVT VT, const X86Subtarget *Subtarget,
10046                                         SelectionDAG &DAG) {
10047   switch (VT.SimpleTy) {
10048   case MVT::v2i64:
10049     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10050   case MVT::v2f64:
10051     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10052   case MVT::v4i32:
10053     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10054   case MVT::v4f32:
10055     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10056   case MVT::v8i16:
10057     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10058   case MVT::v16i8:
10059     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10060
10061   default:
10062     llvm_unreachable("Unimplemented!");
10063   }
10064 }
10065
10066 /// \brief Helper function to test whether a shuffle mask could be
10067 /// simplified by widening the elements being shuffled.
10068 ///
10069 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
10070 /// leaves it in an unspecified state.
10071 ///
10072 /// NOTE: This must handle normal vector shuffle masks and *target* vector
10073 /// shuffle masks. The latter have the special property of a '-2' representing
10074 /// a zero-ed lane of a vector.
10075 static bool canWidenShuffleElements(ArrayRef<int> Mask,
10076                                     SmallVectorImpl<int> &WidenedMask) {
10077   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
10078     // If both elements are undef, its trivial.
10079     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
10080       WidenedMask.push_back(SM_SentinelUndef);
10081       continue;
10082     }
10083
10084     // Check for an undef mask and a mask value properly aligned to fit with
10085     // a pair of values. If we find such a case, use the non-undef mask's value.
10086     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
10087       WidenedMask.push_back(Mask[i + 1] / 2);
10088       continue;
10089     }
10090     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
10091       WidenedMask.push_back(Mask[i] / 2);
10092       continue;
10093     }
10094
10095     // When zeroing, we need to spread the zeroing across both lanes to widen.
10096     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
10097       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
10098           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
10099         WidenedMask.push_back(SM_SentinelZero);
10100         continue;
10101       }
10102       return false;
10103     }
10104
10105     // Finally check if the two mask values are adjacent and aligned with
10106     // a pair.
10107     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
10108       WidenedMask.push_back(Mask[i] / 2);
10109       continue;
10110     }
10111
10112     // Otherwise we can't safely widen the elements used in this shuffle.
10113     return false;
10114   }
10115   assert(WidenedMask.size() == Mask.size() / 2 &&
10116          "Incorrect size of mask after widening the elements!");
10117
10118   return true;
10119 }
10120
10121 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
10122 ///
10123 /// This routine just extracts two subvectors, shuffles them independently, and
10124 /// then concatenates them back together. This should work effectively with all
10125 /// AVX vector shuffle types.
10126 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10127                                           SDValue V2, ArrayRef<int> Mask,
10128                                           SelectionDAG &DAG) {
10129   assert(VT.getSizeInBits() >= 256 &&
10130          "Only for 256-bit or wider vector shuffles!");
10131   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
10132   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
10133
10134   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
10135   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
10136
10137   int NumElements = VT.getVectorNumElements();
10138   int SplitNumElements = NumElements / 2;
10139   MVT ScalarVT = VT.getScalarType();
10140   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
10141
10142   // Rather than splitting build-vectors, just build two narrower build
10143   // vectors. This helps shuffling with splats and zeros.
10144   auto SplitVector = [&](SDValue V) {
10145     while (V.getOpcode() == ISD::BITCAST)
10146       V = V->getOperand(0);
10147
10148     MVT OrigVT = V.getSimpleValueType();
10149     int OrigNumElements = OrigVT.getVectorNumElements();
10150     int OrigSplitNumElements = OrigNumElements / 2;
10151     MVT OrigScalarVT = OrigVT.getScalarType();
10152     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
10153
10154     SDValue LoV, HiV;
10155
10156     auto *BV = dyn_cast<BuildVectorSDNode>(V);
10157     if (!BV) {
10158       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10159                         DAG.getIntPtrConstant(0));
10160       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10161                         DAG.getIntPtrConstant(OrigSplitNumElements));
10162     } else {
10163
10164       SmallVector<SDValue, 16> LoOps, HiOps;
10165       for (int i = 0; i < OrigSplitNumElements; ++i) {
10166         LoOps.push_back(BV->getOperand(i));
10167         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10168       }
10169       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10170       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10171     }
10172     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
10173                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
10174   };
10175
10176   SDValue LoV1, HiV1, LoV2, HiV2;
10177   std::tie(LoV1, HiV1) = SplitVector(V1);
10178   std::tie(LoV2, HiV2) = SplitVector(V2);
10179
10180   // Now create two 4-way blends of these half-width vectors.
10181   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10182     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10183     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10184     for (int i = 0; i < SplitNumElements; ++i) {
10185       int M = HalfMask[i];
10186       if (M >= NumElements) {
10187         if (M >= NumElements + SplitNumElements)
10188           UseHiV2 = true;
10189         else
10190           UseLoV2 = true;
10191         V2BlendMask.push_back(M - NumElements);
10192         V1BlendMask.push_back(-1);
10193         BlendMask.push_back(SplitNumElements + i);
10194       } else if (M >= 0) {
10195         if (M >= SplitNumElements)
10196           UseHiV1 = true;
10197         else
10198           UseLoV1 = true;
10199         V2BlendMask.push_back(-1);
10200         V1BlendMask.push_back(M);
10201         BlendMask.push_back(i);
10202       } else {
10203         V2BlendMask.push_back(-1);
10204         V1BlendMask.push_back(-1);
10205         BlendMask.push_back(-1);
10206       }
10207     }
10208
10209     // Because the lowering happens after all combining takes place, we need to
10210     // manually combine these blend masks as much as possible so that we create
10211     // a minimal number of high-level vector shuffle nodes.
10212
10213     // First try just blending the halves of V1 or V2.
10214     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10215       return DAG.getUNDEF(SplitVT);
10216     if (!UseLoV2 && !UseHiV2)
10217       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10218     if (!UseLoV1 && !UseHiV1)
10219       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10220
10221     SDValue V1Blend, V2Blend;
10222     if (UseLoV1 && UseHiV1) {
10223       V1Blend =
10224         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10225     } else {
10226       // We only use half of V1 so map the usage down into the final blend mask.
10227       V1Blend = UseLoV1 ? LoV1 : HiV1;
10228       for (int i = 0; i < SplitNumElements; ++i)
10229         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10230           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10231     }
10232     if (UseLoV2 && UseHiV2) {
10233       V2Blend =
10234         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10235     } else {
10236       // We only use half of V2 so map the usage down into the final blend mask.
10237       V2Blend = UseLoV2 ? LoV2 : HiV2;
10238       for (int i = 0; i < SplitNumElements; ++i)
10239         if (BlendMask[i] >= SplitNumElements)
10240           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10241     }
10242     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10243   };
10244   SDValue Lo = HalfBlend(LoMask);
10245   SDValue Hi = HalfBlend(HiMask);
10246   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10247 }
10248
10249 /// \brief Either split a vector in halves or decompose the shuffles and the
10250 /// blend.
10251 ///
10252 /// This is provided as a good fallback for many lowerings of non-single-input
10253 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10254 /// between splitting the shuffle into 128-bit components and stitching those
10255 /// back together vs. extracting the single-input shuffles and blending those
10256 /// results.
10257 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10258                                                 SDValue V2, ArrayRef<int> Mask,
10259                                                 SelectionDAG &DAG) {
10260   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10261                                             "lower single-input shuffles as it "
10262                                             "could then recurse on itself.");
10263   int Size = Mask.size();
10264
10265   // If this can be modeled as a broadcast of two elements followed by a blend,
10266   // prefer that lowering. This is especially important because broadcasts can
10267   // often fold with memory operands.
10268   auto DoBothBroadcast = [&] {
10269     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10270     for (int M : Mask)
10271       if (M >= Size) {
10272         if (V2BroadcastIdx == -1)
10273           V2BroadcastIdx = M - Size;
10274         else if (M - Size != V2BroadcastIdx)
10275           return false;
10276       } else if (M >= 0) {
10277         if (V1BroadcastIdx == -1)
10278           V1BroadcastIdx = M;
10279         else if (M != V1BroadcastIdx)
10280           return false;
10281       }
10282     return true;
10283   };
10284   if (DoBothBroadcast())
10285     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10286                                                       DAG);
10287
10288   // If the inputs all stem from a single 128-bit lane of each input, then we
10289   // split them rather than blending because the split will decompose to
10290   // unusually few instructions.
10291   int LaneCount = VT.getSizeInBits() / 128;
10292   int LaneSize = Size / LaneCount;
10293   SmallBitVector LaneInputs[2];
10294   LaneInputs[0].resize(LaneCount, false);
10295   LaneInputs[1].resize(LaneCount, false);
10296   for (int i = 0; i < Size; ++i)
10297     if (Mask[i] >= 0)
10298       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10299   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10300     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10301
10302   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10303   // that the decomposed single-input shuffles don't end up here.
10304   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10305 }
10306
10307 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10308 /// a permutation and blend of those lanes.
10309 ///
10310 /// This essentially blends the out-of-lane inputs to each lane into the lane
10311 /// from a permuted copy of the vector. This lowering strategy results in four
10312 /// instructions in the worst case for a single-input cross lane shuffle which
10313 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10314 /// of. Special cases for each particular shuffle pattern should be handled
10315 /// prior to trying this lowering.
10316 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10317                                                        SDValue V1, SDValue V2,
10318                                                        ArrayRef<int> Mask,
10319                                                        SelectionDAG &DAG) {
10320   // FIXME: This should probably be generalized for 512-bit vectors as well.
10321   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
10322   int LaneSize = Mask.size() / 2;
10323
10324   // If there are only inputs from one 128-bit lane, splitting will in fact be
10325   // less expensive. The flags track wether the given lane contains an element
10326   // that crosses to another lane.
10327   bool LaneCrossing[2] = {false, false};
10328   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10329     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10330       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10331   if (!LaneCrossing[0] || !LaneCrossing[1])
10332     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10333
10334   if (isSingleInputShuffleMask(Mask)) {
10335     SmallVector<int, 32> FlippedBlendMask;
10336     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10337       FlippedBlendMask.push_back(
10338           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10339                                   ? Mask[i]
10340                                   : Mask[i] % LaneSize +
10341                                         (i / LaneSize) * LaneSize + Size));
10342
10343     // Flip the vector, and blend the results which should now be in-lane. The
10344     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10345     // 5 for the high source. The value 3 selects the high half of source 2 and
10346     // the value 2 selects the low half of source 2. We only use source 2 to
10347     // allow folding it into a memory operand.
10348     unsigned PERMMask = 3 | 2 << 4;
10349     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10350                                   V1, DAG.getConstant(PERMMask, MVT::i8));
10351     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10352   }
10353
10354   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10355   // will be handled by the above logic and a blend of the results, much like
10356   // other patterns in AVX.
10357   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10358 }
10359
10360 /// \brief Handle lowering 2-lane 128-bit shuffles.
10361 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10362                                         SDValue V2, ArrayRef<int> Mask,
10363                                         const X86Subtarget *Subtarget,
10364                                         SelectionDAG &DAG) {
10365   // Blends are faster and handle all the non-lane-crossing cases.
10366   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10367                                                 Subtarget, DAG))
10368     return Blend;
10369
10370   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10371                                VT.getVectorNumElements() / 2);
10372   // Check for patterns which can be matched with a single insert of a 128-bit
10373   // subvector.
10374   if (isShuffleEquivalent(Mask, 0, 1, 0, 1) ||
10375       isShuffleEquivalent(Mask, 0, 1, 4, 5)) {
10376     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10377                               DAG.getIntPtrConstant(0));
10378     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10379                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
10380     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10381   }
10382   if (isShuffleEquivalent(Mask, 0, 1, 6, 7)) {
10383     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10384                               DAG.getIntPtrConstant(0));
10385     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
10386                               DAG.getIntPtrConstant(2));
10387     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10388   }
10389
10390   // Otherwise form a 128-bit permutation.
10391   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
10392   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
10393   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10394                      DAG.getConstant(PermMask, MVT::i8));
10395 }
10396
10397 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10398 /// shuffling each lane.
10399 ///
10400 /// This will only succeed when the result of fixing the 128-bit lanes results
10401 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10402 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10403 /// the lane crosses early and then use simpler shuffles within each lane.
10404 ///
10405 /// FIXME: It might be worthwhile at some point to support this without
10406 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10407 /// in x86 only floating point has interesting non-repeating shuffles, and even
10408 /// those are still *marginally* more expensive.
10409 static SDValue lowerVectorShuffleByMerging128BitLanes(
10410     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10411     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10412   assert(!isSingleInputShuffleMask(Mask) &&
10413          "This is only useful with multiple inputs.");
10414
10415   int Size = Mask.size();
10416   int LaneSize = 128 / VT.getScalarSizeInBits();
10417   int NumLanes = Size / LaneSize;
10418   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10419
10420   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10421   // check whether the in-128-bit lane shuffles share a repeating pattern.
10422   SmallVector<int, 4> Lanes;
10423   Lanes.resize(NumLanes, -1);
10424   SmallVector<int, 4> InLaneMask;
10425   InLaneMask.resize(LaneSize, -1);
10426   for (int i = 0; i < Size; ++i) {
10427     if (Mask[i] < 0)
10428       continue;
10429
10430     int j = i / LaneSize;
10431
10432     if (Lanes[j] < 0) {
10433       // First entry we've seen for this lane.
10434       Lanes[j] = Mask[i] / LaneSize;
10435     } else if (Lanes[j] != Mask[i] / LaneSize) {
10436       // This doesn't match the lane selected previously!
10437       return SDValue();
10438     }
10439
10440     // Check that within each lane we have a consistent shuffle mask.
10441     int k = i % LaneSize;
10442     if (InLaneMask[k] < 0) {
10443       InLaneMask[k] = Mask[i] % LaneSize;
10444     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10445       // This doesn't fit a repeating in-lane mask.
10446       return SDValue();
10447     }
10448   }
10449
10450   // First shuffle the lanes into place.
10451   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10452                                 VT.getSizeInBits() / 64);
10453   SmallVector<int, 8> LaneMask;
10454   LaneMask.resize(NumLanes * 2, -1);
10455   for (int i = 0; i < NumLanes; ++i)
10456     if (Lanes[i] >= 0) {
10457       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10458       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10459     }
10460
10461   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
10462   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
10463   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10464
10465   // Cast it back to the type we actually want.
10466   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
10467
10468   // Now do a simple shuffle that isn't lane crossing.
10469   SmallVector<int, 8> NewMask;
10470   NewMask.resize(Size, -1);
10471   for (int i = 0; i < Size; ++i)
10472     if (Mask[i] >= 0)
10473       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10474   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10475          "Must not introduce lane crosses at this point!");
10476
10477   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10478 }
10479
10480 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10481 /// given mask.
10482 ///
10483 /// This returns true if the elements from a particular input are already in the
10484 /// slot required by the given mask and require no permutation.
10485 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10486   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10487   int Size = Mask.size();
10488   for (int i = 0; i < Size; ++i)
10489     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10490       return false;
10491
10492   return true;
10493 }
10494
10495 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10496 ///
10497 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10498 /// isn't available.
10499 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10500                                        const X86Subtarget *Subtarget,
10501                                        SelectionDAG &DAG) {
10502   SDLoc DL(Op);
10503   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10504   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10505   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10506   ArrayRef<int> Mask = SVOp->getMask();
10507   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10508
10509   SmallVector<int, 4> WidenedMask;
10510   if (canWidenShuffleElements(Mask, WidenedMask))
10511     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10512                                     DAG);
10513
10514   if (isSingleInputShuffleMask(Mask)) {
10515     // Check for being able to broadcast a single element.
10516     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
10517                                                           Mask, Subtarget, DAG))
10518       return Broadcast;
10519
10520     // Use low duplicate instructions for masks that match their pattern.
10521     if (isShuffleEquivalent(Mask, 0, 0, 2, 2))
10522       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10523
10524     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10525       // Non-half-crossing single input shuffles can be lowerid with an
10526       // interleaved permutation.
10527       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10528                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10529       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10530                          DAG.getConstant(VPERMILPMask, MVT::i8));
10531     }
10532
10533     // With AVX2 we have direct support for this permutation.
10534     if (Subtarget->hasAVX2())
10535       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10536                          getV4X86ShuffleImm8ForMask(Mask, DAG));
10537
10538     // Otherwise, fall back.
10539     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10540                                                    DAG);
10541   }
10542
10543   // X86 has dedicated unpack instructions that can handle specific blend
10544   // operations: UNPCKH and UNPCKL.
10545   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10546     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10547   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10548     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10549
10550   // If we have a single input to the zero element, insert that into V1 if we
10551   // can do so cheaply.
10552   int NumV2Elements =
10553       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
10554   if (NumV2Elements == 1 && Mask[0] >= 4)
10555     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10556             MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
10557       return Insertion;
10558
10559   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10560                                                 Subtarget, DAG))
10561     return Blend;
10562
10563   // Check if the blend happens to exactly fit that of SHUFPD.
10564   if ((Mask[0] == -1 || Mask[0] < 2) &&
10565       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
10566       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
10567       (Mask[3] == -1 || Mask[3] >= 6)) {
10568     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
10569                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
10570     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
10571                        DAG.getConstant(SHUFPDMask, MVT::i8));
10572   }
10573   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
10574       (Mask[1] == -1 || Mask[1] < 2) &&
10575       (Mask[2] == -1 || Mask[2] >= 6) &&
10576       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
10577     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
10578                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
10579     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
10580                        DAG.getConstant(SHUFPDMask, MVT::i8));
10581   }
10582
10583   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10584   // shuffle. However, if we have AVX2 and either inputs are already in place,
10585   // we will be able to shuffle even across lanes the other input in a single
10586   // instruction so skip this pattern.
10587   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10588                                  isShuffleMaskInputInPlace(1, Mask))))
10589     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10590             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10591       return Result;
10592
10593   // If we have AVX2 then we always want to lower with a blend because an v4 we
10594   // can fully permute the elements.
10595   if (Subtarget->hasAVX2())
10596     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10597                                                       Mask, DAG);
10598
10599   // Otherwise fall back on generic lowering.
10600   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10601 }
10602
10603 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10604 ///
10605 /// This routine is only called when we have AVX2 and thus a reasonable
10606 /// instruction set for v4i64 shuffling..
10607 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10608                                        const X86Subtarget *Subtarget,
10609                                        SelectionDAG &DAG) {
10610   SDLoc DL(Op);
10611   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10612   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10613   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10614   ArrayRef<int> Mask = SVOp->getMask();
10615   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10616   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10617
10618   SmallVector<int, 4> WidenedMask;
10619   if (canWidenShuffleElements(Mask, WidenedMask))
10620     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10621                                     DAG);
10622
10623   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10624                                                 Subtarget, DAG))
10625     return Blend;
10626
10627   // Check for being able to broadcast a single element.
10628   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
10629                                                         Mask, Subtarget, DAG))
10630     return Broadcast;
10631
10632   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10633   // use lower latency instructions that will operate on both 128-bit lanes.
10634   SmallVector<int, 2> RepeatedMask;
10635   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10636     if (isSingleInputShuffleMask(Mask)) {
10637       int PSHUFDMask[] = {-1, -1, -1, -1};
10638       for (int i = 0; i < 2; ++i)
10639         if (RepeatedMask[i] >= 0) {
10640           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10641           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10642         }
10643       return DAG.getNode(
10644           ISD::BITCAST, DL, MVT::v4i64,
10645           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10646                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
10647                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
10648     }
10649
10650     // Use dedicated unpack instructions for masks that match their pattern.
10651     if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10652       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10653     if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10654       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10655   }
10656
10657   // AVX2 provides a direct instruction for permuting a single input across
10658   // lanes.
10659   if (isSingleInputShuffleMask(Mask))
10660     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10661                        getV4X86ShuffleImm8ForMask(Mask, DAG));
10662
10663   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10664   // shuffle. However, if we have AVX2 and either inputs are already in place,
10665   // we will be able to shuffle even across lanes the other input in a single
10666   // instruction so skip this pattern.
10667   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10668                                  isShuffleMaskInputInPlace(1, Mask))))
10669     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10670             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10671       return Result;
10672
10673   // Otherwise fall back on generic blend lowering.
10674   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10675                                                     Mask, DAG);
10676 }
10677
10678 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10679 ///
10680 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10681 /// isn't available.
10682 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10683                                        const X86Subtarget *Subtarget,
10684                                        SelectionDAG &DAG) {
10685   SDLoc DL(Op);
10686   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10687   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10688   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10689   ArrayRef<int> Mask = SVOp->getMask();
10690   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10691
10692   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10693                                                 Subtarget, DAG))
10694     return Blend;
10695
10696   // Check for being able to broadcast a single element.
10697   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
10698                                                         Mask, Subtarget, DAG))
10699     return Broadcast;
10700
10701   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10702   // options to efficiently lower the shuffle.
10703   SmallVector<int, 4> RepeatedMask;
10704   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10705     assert(RepeatedMask.size() == 4 &&
10706            "Repeated masks must be half the mask width!");
10707
10708     // Use even/odd duplicate instructions for masks that match their pattern.
10709     if (isShuffleEquivalent(Mask, 0, 0, 2, 2, 4, 4, 6, 6))
10710       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10711     if (isShuffleEquivalent(Mask, 1, 1, 3, 3, 5, 5, 7, 7))
10712       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10713
10714     if (isSingleInputShuffleMask(Mask))
10715       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10716                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10717
10718     // Use dedicated unpack instructions for masks that match their pattern.
10719     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10720       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10721     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10722       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10723
10724     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10725     // have already handled any direct blends. We also need to squash the
10726     // repeated mask into a simulated v4f32 mask.
10727     for (int i = 0; i < 4; ++i)
10728       if (RepeatedMask[i] >= 8)
10729         RepeatedMask[i] -= 4;
10730     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10731   }
10732
10733   // If we have a single input shuffle with different shuffle patterns in the
10734   // two 128-bit lanes use the variable mask to VPERMILPS.
10735   if (isSingleInputShuffleMask(Mask)) {
10736     SDValue VPermMask[8];
10737     for (int i = 0; i < 8; ++i)
10738       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10739                                  : DAG.getConstant(Mask[i], MVT::i32);
10740     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10741       return DAG.getNode(
10742           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10743           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10744
10745     if (Subtarget->hasAVX2())
10746       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
10747                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
10748                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
10749                                                  MVT::v8i32, VPermMask)),
10750                          V1);
10751
10752     // Otherwise, fall back.
10753     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10754                                                    DAG);
10755   }
10756
10757   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10758   // shuffle.
10759   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10760           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10761     return Result;
10762
10763   // If we have AVX2 then we always want to lower with a blend because at v8 we
10764   // can fully permute the elements.
10765   if (Subtarget->hasAVX2())
10766     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10767                                                       Mask, DAG);
10768
10769   // Otherwise fall back on generic lowering.
10770   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10771 }
10772
10773 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10774 ///
10775 /// This routine is only called when we have AVX2 and thus a reasonable
10776 /// instruction set for v8i32 shuffling..
10777 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10778                                        const X86Subtarget *Subtarget,
10779                                        SelectionDAG &DAG) {
10780   SDLoc DL(Op);
10781   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10782   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10783   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10784   ArrayRef<int> Mask = SVOp->getMask();
10785   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10786   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10787
10788   // Whenever we can lower this as a zext, that instruction is strictly faster
10789   // than any alternative. It also allows us to fold memory operands into the
10790   // shuffle in many cases.
10791   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10792                                                          Mask, Subtarget, DAG))
10793     return ZExt;
10794
10795   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10796                                                 Subtarget, DAG))
10797     return Blend;
10798
10799   // Check for being able to broadcast a single element.
10800   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
10801                                                         Mask, Subtarget, DAG))
10802     return Broadcast;
10803
10804   // If the shuffle mask is repeated in each 128-bit lane we can use more
10805   // efficient instructions that mirror the shuffles across the two 128-bit
10806   // lanes.
10807   SmallVector<int, 4> RepeatedMask;
10808   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10809     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10810     if (isSingleInputShuffleMask(Mask))
10811       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10812                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10813
10814     // Use dedicated unpack instructions for masks that match their pattern.
10815     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10816       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10817     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10818       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10819   }
10820
10821   // If the shuffle patterns aren't repeated but it is a single input, directly
10822   // generate a cross-lane VPERMD instruction.
10823   if (isSingleInputShuffleMask(Mask)) {
10824     SDValue VPermMask[8];
10825     for (int i = 0; i < 8; ++i)
10826       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10827                                  : DAG.getConstant(Mask[i], MVT::i32);
10828     return DAG.getNode(
10829         X86ISD::VPERMV, DL, MVT::v8i32,
10830         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10831   }
10832
10833   // Try to use bit shift instructions.
10834   if (SDValue Shift = lowerVectorShuffleAsBitShift(
10835           DL, MVT::v8i32, V1, V2, Mask, DAG))
10836     return Shift;
10837
10838   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10839   // shuffle.
10840   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10841           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10842     return Result;
10843
10844   // Otherwise fall back on generic blend lowering.
10845   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10846                                                     Mask, DAG);
10847 }
10848
10849 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10850 ///
10851 /// This routine is only called when we have AVX2 and thus a reasonable
10852 /// instruction set for v16i16 shuffling..
10853 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10854                                         const X86Subtarget *Subtarget,
10855                                         SelectionDAG &DAG) {
10856   SDLoc DL(Op);
10857   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10858   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10859   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10860   ArrayRef<int> Mask = SVOp->getMask();
10861   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10862   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10863
10864   // Whenever we can lower this as a zext, that instruction is strictly faster
10865   // than any alternative. It also allows us to fold memory operands into the
10866   // shuffle in many cases.
10867   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10868                                                          Mask, Subtarget, DAG))
10869     return ZExt;
10870
10871   // Check for being able to broadcast a single element.
10872   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
10873                                                         Mask, Subtarget, DAG))
10874     return Broadcast;
10875
10876   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10877                                                 Subtarget, DAG))
10878     return Blend;
10879
10880   // Use dedicated unpack instructions for masks that match their pattern.
10881   if (isShuffleEquivalent(Mask,
10882                           // First 128-bit lane:
10883                           0, 16, 1, 17, 2, 18, 3, 19,
10884                           // Second 128-bit lane:
10885                           8, 24, 9, 25, 10, 26, 11, 27))
10886     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10887   if (isShuffleEquivalent(Mask,
10888                           // First 128-bit lane:
10889                           4, 20, 5, 21, 6, 22, 7, 23,
10890                           // Second 128-bit lane:
10891                           12, 28, 13, 29, 14, 30, 15, 31))
10892     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10893
10894   if (isSingleInputShuffleMask(Mask)) {
10895     // There are no generalized cross-lane shuffle operations available on i16
10896     // element types.
10897     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10898       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10899                                                      Mask, DAG);
10900
10901     SDValue PSHUFBMask[32];
10902     for (int i = 0; i < 16; ++i) {
10903       if (Mask[i] == -1) {
10904         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10905         continue;
10906       }
10907
10908       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10909       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10910       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
10911       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
10912     }
10913     return DAG.getNode(
10914         ISD::BITCAST, DL, MVT::v16i16,
10915         DAG.getNode(
10916             X86ISD::PSHUFB, DL, MVT::v32i8,
10917             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
10918             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
10919   }
10920
10921   // Try to use bit shift instructions.
10922   if (SDValue Shift = lowerVectorShuffleAsBitShift(
10923           DL, MVT::v16i16, V1, V2, Mask, DAG))
10924     return Shift;
10925
10926   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10927   // shuffle.
10928   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10929           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10930     return Result;
10931
10932   // Otherwise fall back on generic lowering.
10933   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10934 }
10935
10936 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10937 ///
10938 /// This routine is only called when we have AVX2 and thus a reasonable
10939 /// instruction set for v32i8 shuffling..
10940 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10941                                        const X86Subtarget *Subtarget,
10942                                        SelectionDAG &DAG) {
10943   SDLoc DL(Op);
10944   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10945   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10946   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10947   ArrayRef<int> Mask = SVOp->getMask();
10948   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10949   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10950
10951   // Whenever we can lower this as a zext, that instruction is strictly faster
10952   // than any alternative. It also allows us to fold memory operands into the
10953   // shuffle in many cases.
10954   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10955                                                          Mask, Subtarget, DAG))
10956     return ZExt;
10957
10958   // Check for being able to broadcast a single element.
10959   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
10960                                                         Mask, Subtarget, DAG))
10961     return Broadcast;
10962
10963   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10964                                                 Subtarget, DAG))
10965     return Blend;
10966
10967   // Use dedicated unpack instructions for masks that match their pattern.
10968   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10969   // 256-bit lanes.
10970   if (isShuffleEquivalent(
10971           Mask,
10972           // First 128-bit lane:
10973           0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10974           // Second 128-bit lane:
10975           16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55))
10976     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10977   if (isShuffleEquivalent(
10978           Mask,
10979           // First 128-bit lane:
10980           8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10981           // Second 128-bit lane:
10982           24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63))
10983     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10984
10985   if (isSingleInputShuffleMask(Mask)) {
10986     // There are no generalized cross-lane shuffle operations available on i8
10987     // element types.
10988     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10989       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10990                                                      Mask, DAG);
10991
10992     SDValue PSHUFBMask[32];
10993     for (int i = 0; i < 32; ++i)
10994       PSHUFBMask[i] =
10995           Mask[i] < 0
10996               ? DAG.getUNDEF(MVT::i8)
10997               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
10998
10999     return DAG.getNode(
11000         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
11001         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
11002   }
11003
11004   // Try to use bit shift instructions.
11005   if (SDValue Shift = lowerVectorShuffleAsBitShift(
11006           DL, MVT::v32i8, V1, V2, Mask, DAG))
11007     return Shift;
11008
11009   // Try to simplify this by merging 128-bit lanes to enable a lane-based
11010   // shuffle.
11011   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11012           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11013     return Result;
11014
11015   // Otherwise fall back on generic lowering.
11016   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11017 }
11018
11019 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11020 ///
11021 /// This routine either breaks down the specific type of a 256-bit x86 vector
11022 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11023 /// together based on the available instructions.
11024 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11025                                         MVT VT, const X86Subtarget *Subtarget,
11026                                         SelectionDAG &DAG) {
11027   SDLoc DL(Op);
11028   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11029   ArrayRef<int> Mask = SVOp->getMask();
11030
11031   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
11032   // check for those subtargets here and avoid much of the subtarget querying in
11033   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
11034   // ability to manipulate a 256-bit vector with integer types. Since we'll use
11035   // floating point types there eventually, just immediately cast everything to
11036   // a float and operate entirely in that domain.
11037   if (VT.isInteger() && !Subtarget->hasAVX2()) {
11038     int ElementBits = VT.getScalarSizeInBits();
11039     if (ElementBits < 32)
11040       // No floating point type available, decompose into 128-bit vectors.
11041       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11042
11043     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11044                                 VT.getVectorNumElements());
11045     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
11046     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
11047     return DAG.getNode(ISD::BITCAST, DL, VT,
11048                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11049   }
11050
11051   switch (VT.SimpleTy) {
11052   case MVT::v4f64:
11053     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11054   case MVT::v4i64:
11055     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11056   case MVT::v8f32:
11057     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11058   case MVT::v8i32:
11059     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11060   case MVT::v16i16:
11061     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11062   case MVT::v32i8:
11063     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11064
11065   default:
11066     llvm_unreachable("Not a valid 256-bit x86 vector type!");
11067   }
11068 }
11069
11070 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11071 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11072                                        const X86Subtarget *Subtarget,
11073                                        SelectionDAG &DAG) {
11074   SDLoc DL(Op);
11075   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11076   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11077   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11078   ArrayRef<int> Mask = SVOp->getMask();
11079   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11080
11081   // X86 has dedicated unpack instructions that can handle specific blend
11082   // operations: UNPCKH and UNPCKL.
11083   if (isShuffleEquivalent(Mask, 0, 8, 2, 10, 4, 12, 6, 14))
11084     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
11085   if (isShuffleEquivalent(Mask, 1, 9, 3, 11, 5, 13, 7, 15))
11086     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
11087
11088   // FIXME: Implement direct support for this type!
11089   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
11090 }
11091
11092 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11093 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11094                                        const X86Subtarget *Subtarget,
11095                                        SelectionDAG &DAG) {
11096   SDLoc DL(Op);
11097   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11098   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11099   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11100   ArrayRef<int> Mask = SVOp->getMask();
11101   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11102
11103   // Use dedicated unpack instructions for masks that match their pattern.
11104   if (isShuffleEquivalent(Mask,
11105                           0, 16, 1, 17, 4, 20, 5, 21,
11106                           8, 24, 9, 25, 12, 28, 13, 29))
11107     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
11108   if (isShuffleEquivalent(Mask,
11109                           2, 18, 3, 19, 6, 22, 7, 23,
11110                           10, 26, 11, 27, 14, 30, 15, 31))
11111     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
11112
11113   // FIXME: Implement direct support for this type!
11114   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
11115 }
11116
11117 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11118 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11119                                        const X86Subtarget *Subtarget,
11120                                        SelectionDAG &DAG) {
11121   SDLoc DL(Op);
11122   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11123   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11124   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11125   ArrayRef<int> Mask = SVOp->getMask();
11126   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11127
11128   // X86 has dedicated unpack instructions that can handle specific blend
11129   // operations: UNPCKH and UNPCKL.
11130   if (isShuffleEquivalent(Mask, 0, 8, 2, 10, 4, 12, 6, 14))
11131     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
11132   if (isShuffleEquivalent(Mask, 1, 9, 3, 11, 5, 13, 7, 15))
11133     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
11134
11135   // FIXME: Implement direct support for this type!
11136   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
11137 }
11138
11139 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11140 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11141                                        const X86Subtarget *Subtarget,
11142                                        SelectionDAG &DAG) {
11143   SDLoc DL(Op);
11144   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11145   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11146   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11147   ArrayRef<int> Mask = SVOp->getMask();
11148   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11149
11150   // Use dedicated unpack instructions for masks that match their pattern.
11151   if (isShuffleEquivalent(Mask,
11152                           0, 16, 1, 17, 4, 20, 5, 21,
11153                           8, 24, 9, 25, 12, 28, 13, 29))
11154     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
11155   if (isShuffleEquivalent(Mask,
11156                           2, 18, 3, 19, 6, 22, 7, 23,
11157                           10, 26, 11, 27, 14, 30, 15, 31))
11158     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
11159
11160   // FIXME: Implement direct support for this type!
11161   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
11162 }
11163
11164 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11165 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11166                                         const X86Subtarget *Subtarget,
11167                                         SelectionDAG &DAG) {
11168   SDLoc DL(Op);
11169   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11170   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11171   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11172   ArrayRef<int> Mask = SVOp->getMask();
11173   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11174   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11175
11176   // FIXME: Implement direct support for this type!
11177   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
11178 }
11179
11180 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11181 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11182                                        const X86Subtarget *Subtarget,
11183                                        SelectionDAG &DAG) {
11184   SDLoc DL(Op);
11185   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11186   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11187   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11188   ArrayRef<int> Mask = SVOp->getMask();
11189   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11190   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11191
11192   // FIXME: Implement direct support for this type!
11193   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11194 }
11195
11196 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11197 ///
11198 /// This routine either breaks down the specific type of a 512-bit x86 vector
11199 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11200 /// together based on the available instructions.
11201 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11202                                         MVT VT, const X86Subtarget *Subtarget,
11203                                         SelectionDAG &DAG) {
11204   SDLoc DL(Op);
11205   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11206   ArrayRef<int> Mask = SVOp->getMask();
11207   assert(Subtarget->hasAVX512() &&
11208          "Cannot lower 512-bit vectors w/ basic ISA!");
11209
11210   // Check for being able to broadcast a single element.
11211   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
11212                                                         Mask, Subtarget, DAG))
11213     return Broadcast;
11214
11215   // Dispatch to each element type for lowering. If we don't have supprot for
11216   // specific element type shuffles at 512 bits, immediately split them and
11217   // lower them. Each lowering routine of a given type is allowed to assume that
11218   // the requisite ISA extensions for that element type are available.
11219   switch (VT.SimpleTy) {
11220   case MVT::v8f64:
11221     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11222   case MVT::v16f32:
11223     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11224   case MVT::v8i64:
11225     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11226   case MVT::v16i32:
11227     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11228   case MVT::v32i16:
11229     if (Subtarget->hasBWI())
11230       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11231     break;
11232   case MVT::v64i8:
11233     if (Subtarget->hasBWI())
11234       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11235     break;
11236
11237   default:
11238     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11239   }
11240
11241   // Otherwise fall back on splitting.
11242   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11243 }
11244
11245 /// \brief Top-level lowering for x86 vector shuffles.
11246 ///
11247 /// This handles decomposition, canonicalization, and lowering of all x86
11248 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11249 /// above in helper routines. The canonicalization attempts to widen shuffles
11250 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11251 /// s.t. only one of the two inputs needs to be tested, etc.
11252 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11253                                   SelectionDAG &DAG) {
11254   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11255   ArrayRef<int> Mask = SVOp->getMask();
11256   SDValue V1 = Op.getOperand(0);
11257   SDValue V2 = Op.getOperand(1);
11258   MVT VT = Op.getSimpleValueType();
11259   int NumElements = VT.getVectorNumElements();
11260   SDLoc dl(Op);
11261
11262   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
11263
11264   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11265   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11266   if (V1IsUndef && V2IsUndef)
11267     return DAG.getUNDEF(VT);
11268
11269   // When we create a shuffle node we put the UNDEF node to second operand,
11270   // but in some cases the first operand may be transformed to UNDEF.
11271   // In this case we should just commute the node.
11272   if (V1IsUndef)
11273     return DAG.getCommutedVectorShuffle(*SVOp);
11274
11275   // Check for non-undef masks pointing at an undef vector and make the masks
11276   // undef as well. This makes it easier to match the shuffle based solely on
11277   // the mask.
11278   if (V2IsUndef)
11279     for (int M : Mask)
11280       if (M >= NumElements) {
11281         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11282         for (int &M : NewMask)
11283           if (M >= NumElements)
11284             M = -1;
11285         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11286       }
11287
11288   // We actually see shuffles that are entirely re-arrangements of a set of
11289   // zero inputs. This mostly happens while decomposing complex shuffles into
11290   // simple ones. Directly lower these as a buildvector of zeros.
11291   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11292   if (Zeroable.all())
11293     return getZeroVector(VT, Subtarget, DAG, dl);
11294
11295   // Try to collapse shuffles into using a vector type with fewer elements but
11296   // wider element types. We cap this to not form integers or floating point
11297   // elements wider than 64 bits, but it might be interesting to form i128
11298   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11299   SmallVector<int, 16> WidenedMask;
11300   if (VT.getScalarSizeInBits() < 64 &&
11301       canWidenShuffleElements(Mask, WidenedMask)) {
11302     MVT NewEltVT = VT.isFloatingPoint()
11303                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11304                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11305     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11306     // Make sure that the new vector type is legal. For example, v2f64 isn't
11307     // legal on SSE1.
11308     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11309       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
11310       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
11311       return DAG.getNode(ISD::BITCAST, dl, VT,
11312                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11313     }
11314   }
11315
11316   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11317   for (int M : SVOp->getMask())
11318     if (M < 0)
11319       ++NumUndefElements;
11320     else if (M < NumElements)
11321       ++NumV1Elements;
11322     else
11323       ++NumV2Elements;
11324
11325   // Commute the shuffle as needed such that more elements come from V1 than
11326   // V2. This allows us to match the shuffle pattern strictly on how many
11327   // elements come from V1 without handling the symmetric cases.
11328   if (NumV2Elements > NumV1Elements)
11329     return DAG.getCommutedVectorShuffle(*SVOp);
11330
11331   // When the number of V1 and V2 elements are the same, try to minimize the
11332   // number of uses of V2 in the low half of the vector. When that is tied,
11333   // ensure that the sum of indices for V1 is equal to or lower than the sum
11334   // indices for V2. When those are equal, try to ensure that the number of odd
11335   // indices for V1 is lower than the number of odd indices for V2.
11336   if (NumV1Elements == NumV2Elements) {
11337     int LowV1Elements = 0, LowV2Elements = 0;
11338     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11339       if (M >= NumElements)
11340         ++LowV2Elements;
11341       else if (M >= 0)
11342         ++LowV1Elements;
11343     if (LowV2Elements > LowV1Elements) {
11344       return DAG.getCommutedVectorShuffle(*SVOp);
11345     } else if (LowV2Elements == LowV1Elements) {
11346       int SumV1Indices = 0, SumV2Indices = 0;
11347       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11348         if (SVOp->getMask()[i] >= NumElements)
11349           SumV2Indices += i;
11350         else if (SVOp->getMask()[i] >= 0)
11351           SumV1Indices += i;
11352       if (SumV2Indices < SumV1Indices) {
11353         return DAG.getCommutedVectorShuffle(*SVOp);
11354       } else if (SumV2Indices == SumV1Indices) {
11355         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11356         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11357           if (SVOp->getMask()[i] >= NumElements)
11358             NumV2OddIndices += i % 2;
11359           else if (SVOp->getMask()[i] >= 0)
11360             NumV1OddIndices += i % 2;
11361         if (NumV2OddIndices < NumV1OddIndices)
11362           return DAG.getCommutedVectorShuffle(*SVOp);
11363       }
11364     }
11365   }
11366
11367   // For each vector width, delegate to a specialized lowering routine.
11368   if (VT.getSizeInBits() == 128)
11369     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11370
11371   if (VT.getSizeInBits() == 256)
11372     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11373
11374   // Force AVX-512 vectors to be scalarized for now.
11375   // FIXME: Implement AVX-512 support!
11376   if (VT.getSizeInBits() == 512)
11377     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11378
11379   llvm_unreachable("Unimplemented!");
11380 }
11381
11382
11383 //===----------------------------------------------------------------------===//
11384 // Legacy vector shuffle lowering
11385 //
11386 // This code is the legacy code handling vector shuffles until the above
11387 // replaces its functionality and performance.
11388 //===----------------------------------------------------------------------===//
11389
11390 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
11391                         bool hasInt256, unsigned *MaskOut = nullptr) {
11392   MVT EltVT = VT.getVectorElementType();
11393
11394   // There is no blend with immediate in AVX-512.
11395   if (VT.is512BitVector())
11396     return false;
11397
11398   if (!hasSSE41 || EltVT == MVT::i8)
11399     return false;
11400   if (!hasInt256 && VT == MVT::v16i16)
11401     return false;
11402
11403   unsigned MaskValue = 0;
11404   unsigned NumElems = VT.getVectorNumElements();
11405   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11406   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11407   unsigned NumElemsInLane = NumElems / NumLanes;
11408
11409   // Blend for v16i16 should be symmetric for both lanes.
11410   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11411
11412     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
11413     int EltIdx = MaskVals[i];
11414
11415     if ((EltIdx < 0 || EltIdx == (int)i) &&
11416         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
11417       continue;
11418
11419     if (((unsigned)EltIdx == (i + NumElems)) &&
11420         (SndLaneEltIdx < 0 ||
11421          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
11422       MaskValue |= (1 << i);
11423     else
11424       return false;
11425   }
11426
11427   if (MaskOut)
11428     *MaskOut = MaskValue;
11429   return true;
11430 }
11431
11432 // Try to lower a shuffle node into a simple blend instruction.
11433 // This function assumes isBlendMask returns true for this
11434 // SuffleVectorSDNode
11435 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
11436                                           unsigned MaskValue,
11437                                           const X86Subtarget *Subtarget,
11438                                           SelectionDAG &DAG) {
11439   MVT VT = SVOp->getSimpleValueType(0);
11440   MVT EltVT = VT.getVectorElementType();
11441   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
11442                      Subtarget->hasInt256() && "Trying to lower a "
11443                                                "VECTOR_SHUFFLE to a Blend but "
11444                                                "with the wrong mask"));
11445   SDValue V1 = SVOp->getOperand(0);
11446   SDValue V2 = SVOp->getOperand(1);
11447   SDLoc dl(SVOp);
11448   unsigned NumElems = VT.getVectorNumElements();
11449
11450   // Convert i32 vectors to floating point if it is not AVX2.
11451   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
11452   MVT BlendVT = VT;
11453   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
11454     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
11455                                NumElems);
11456     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
11457     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
11458   }
11459
11460   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
11461                             DAG.getConstant(MaskValue, MVT::i32));
11462   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
11463 }
11464
11465 /// In vector type \p VT, return true if the element at index \p InputIdx
11466 /// falls on a different 128-bit lane than \p OutputIdx.
11467 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
11468                                      unsigned OutputIdx) {
11469   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
11470   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
11471 }
11472
11473 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
11474 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
11475 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
11476 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
11477 /// zero.
11478 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
11479                          SelectionDAG &DAG) {
11480   MVT VT = V1.getSimpleValueType();
11481   assert(VT.is128BitVector() || VT.is256BitVector());
11482
11483   MVT EltVT = VT.getVectorElementType();
11484   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
11485   unsigned NumElts = VT.getVectorNumElements();
11486
11487   SmallVector<SDValue, 32> PshufbMask;
11488   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
11489     int InputIdx = MaskVals[OutputIdx];
11490     unsigned InputByteIdx;
11491
11492     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
11493       InputByteIdx = 0x80;
11494     else {
11495       // Cross lane is not allowed.
11496       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
11497         return SDValue();
11498       InputByteIdx = InputIdx * EltSizeInBytes;
11499       // Index is an byte offset within the 128-bit lane.
11500       InputByteIdx &= 0xf;
11501     }
11502
11503     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
11504       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
11505       if (InputByteIdx != 0x80)
11506         ++InputByteIdx;
11507     }
11508   }
11509
11510   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
11511   if (ShufVT != VT)
11512     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
11513   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
11514                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
11515 }
11516
11517 // v8i16 shuffles - Prefer shuffles in the following order:
11518 // 1. [all]   pshuflw, pshufhw, optional move
11519 // 2. [ssse3] 1 x pshufb
11520 // 3. [ssse3] 2 x pshufb + 1 x por
11521 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
11522 static SDValue
11523 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
11524                          SelectionDAG &DAG) {
11525   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11526   SDValue V1 = SVOp->getOperand(0);
11527   SDValue V2 = SVOp->getOperand(1);
11528   SDLoc dl(SVOp);
11529   SmallVector<int, 8> MaskVals;
11530
11531   // Determine if more than 1 of the words in each of the low and high quadwords
11532   // of the result come from the same quadword of one of the two inputs.  Undef
11533   // mask values count as coming from any quadword, for better codegen.
11534   //
11535   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
11536   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
11537   unsigned LoQuad[] = { 0, 0, 0, 0 };
11538   unsigned HiQuad[] = { 0, 0, 0, 0 };
11539   // Indices of quads used.
11540   std::bitset<4> InputQuads;
11541   for (unsigned i = 0; i < 8; ++i) {
11542     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
11543     int EltIdx = SVOp->getMaskElt(i);
11544     MaskVals.push_back(EltIdx);
11545     if (EltIdx < 0) {
11546       ++Quad[0];
11547       ++Quad[1];
11548       ++Quad[2];
11549       ++Quad[3];
11550       continue;
11551     }
11552     ++Quad[EltIdx / 4];
11553     InputQuads.set(EltIdx / 4);
11554   }
11555
11556   int BestLoQuad = -1;
11557   unsigned MaxQuad = 1;
11558   for (unsigned i = 0; i < 4; ++i) {
11559     if (LoQuad[i] > MaxQuad) {
11560       BestLoQuad = i;
11561       MaxQuad = LoQuad[i];
11562     }
11563   }
11564
11565   int BestHiQuad = -1;
11566   MaxQuad = 1;
11567   for (unsigned i = 0; i < 4; ++i) {
11568     if (HiQuad[i] > MaxQuad) {
11569       BestHiQuad = i;
11570       MaxQuad = HiQuad[i];
11571     }
11572   }
11573
11574   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
11575   // of the two input vectors, shuffle them into one input vector so only a
11576   // single pshufb instruction is necessary. If there are more than 2 input
11577   // quads, disable the next transformation since it does not help SSSE3.
11578   bool V1Used = InputQuads[0] || InputQuads[1];
11579   bool V2Used = InputQuads[2] || InputQuads[3];
11580   if (Subtarget->hasSSSE3()) {
11581     if (InputQuads.count() == 2 && V1Used && V2Used) {
11582       BestLoQuad = InputQuads[0] ? 0 : 1;
11583       BestHiQuad = InputQuads[2] ? 2 : 3;
11584     }
11585     if (InputQuads.count() > 2) {
11586       BestLoQuad = -1;
11587       BestHiQuad = -1;
11588     }
11589   }
11590
11591   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
11592   // the shuffle mask.  If a quad is scored as -1, that means that it contains
11593   // words from all 4 input quadwords.
11594   SDValue NewV;
11595   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
11596     int MaskV[] = {
11597       BestLoQuad < 0 ? 0 : BestLoQuad,
11598       BestHiQuad < 0 ? 1 : BestHiQuad
11599     };
11600     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
11601                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
11602                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
11603     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
11604
11605     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
11606     // source words for the shuffle, to aid later transformations.
11607     bool AllWordsInNewV = true;
11608     bool InOrder[2] = { true, true };
11609     for (unsigned i = 0; i != 8; ++i) {
11610       int idx = MaskVals[i];
11611       if (idx != (int)i)
11612         InOrder[i/4] = false;
11613       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
11614         continue;
11615       AllWordsInNewV = false;
11616       break;
11617     }
11618
11619     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
11620     if (AllWordsInNewV) {
11621       for (int i = 0; i != 8; ++i) {
11622         int idx = MaskVals[i];
11623         if (idx < 0)
11624           continue;
11625         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
11626         if ((idx != i) && idx < 4)
11627           pshufhw = false;
11628         if ((idx != i) && idx > 3)
11629           pshuflw = false;
11630       }
11631       V1 = NewV;
11632       V2Used = false;
11633       BestLoQuad = 0;
11634       BestHiQuad = 1;
11635     }
11636
11637     // If we've eliminated the use of V2, and the new mask is a pshuflw or
11638     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
11639     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
11640       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
11641       unsigned TargetMask = 0;
11642       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
11643                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
11644       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11645       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
11646                              getShufflePSHUFLWImmediate(SVOp);
11647       V1 = NewV.getOperand(0);
11648       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
11649     }
11650   }
11651
11652   // Promote splats to a larger type which usually leads to more efficient code.
11653   // FIXME: Is this true if pshufb is available?
11654   if (SVOp->isSplat())
11655     return PromoteSplat(SVOp, DAG);
11656
11657   // If we have SSSE3, and all words of the result are from 1 input vector,
11658   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
11659   // is present, fall back to case 4.
11660   if (Subtarget->hasSSSE3()) {
11661     SmallVector<SDValue,16> pshufbMask;
11662
11663     // If we have elements from both input vectors, set the high bit of the
11664     // shuffle mask element to zero out elements that come from V2 in the V1
11665     // mask, and elements that come from V1 in the V2 mask, so that the two
11666     // results can be OR'd together.
11667     bool TwoInputs = V1Used && V2Used;
11668     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
11669     if (!TwoInputs)
11670       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11671
11672     // Calculate the shuffle mask for the second input, shuffle it, and
11673     // OR it with the first shuffled input.
11674     CommuteVectorShuffleMask(MaskVals, 8);
11675     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
11676     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11677     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11678   }
11679
11680   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
11681   // and update MaskVals with new element order.
11682   std::bitset<8> InOrder;
11683   if (BestLoQuad >= 0) {
11684     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
11685     for (int i = 0; i != 4; ++i) {
11686       int idx = MaskVals[i];
11687       if (idx < 0) {
11688         InOrder.set(i);
11689       } else if ((idx / 4) == BestLoQuad) {
11690         MaskV[i] = idx & 3;
11691         InOrder.set(i);
11692       }
11693     }
11694     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11695                                 &MaskV[0]);
11696
11697     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11698       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11699       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
11700                                   NewV.getOperand(0),
11701                                   getShufflePSHUFLWImmediate(SVOp), DAG);
11702     }
11703   }
11704
11705   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
11706   // and update MaskVals with the new element order.
11707   if (BestHiQuad >= 0) {
11708     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
11709     for (unsigned i = 4; i != 8; ++i) {
11710       int idx = MaskVals[i];
11711       if (idx < 0) {
11712         InOrder.set(i);
11713       } else if ((idx / 4) == BestHiQuad) {
11714         MaskV[i] = (idx & 3) + 4;
11715         InOrder.set(i);
11716       }
11717     }
11718     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11719                                 &MaskV[0]);
11720
11721     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11722       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11723       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
11724                                   NewV.getOperand(0),
11725                                   getShufflePSHUFHWImmediate(SVOp), DAG);
11726     }
11727   }
11728
11729   // In case BestHi & BestLo were both -1, which means each quadword has a word
11730   // from each of the four input quadwords, calculate the InOrder bitvector now
11731   // before falling through to the insert/extract cleanup.
11732   if (BestLoQuad == -1 && BestHiQuad == -1) {
11733     NewV = V1;
11734     for (int i = 0; i != 8; ++i)
11735       if (MaskVals[i] < 0 || MaskVals[i] == i)
11736         InOrder.set(i);
11737   }
11738
11739   // The other elements are put in the right place using pextrw and pinsrw.
11740   for (unsigned i = 0; i != 8; ++i) {
11741     if (InOrder[i])
11742       continue;
11743     int EltIdx = MaskVals[i];
11744     if (EltIdx < 0)
11745       continue;
11746     SDValue ExtOp = (EltIdx < 8) ?
11747       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
11748                   DAG.getIntPtrConstant(EltIdx)) :
11749       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
11750                   DAG.getIntPtrConstant(EltIdx - 8));
11751     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
11752                        DAG.getIntPtrConstant(i));
11753   }
11754   return NewV;
11755 }
11756
11757 /// \brief v16i16 shuffles
11758 ///
11759 /// FIXME: We only support generation of a single pshufb currently.  We can
11760 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
11761 /// well (e.g 2 x pshufb + 1 x por).
11762 static SDValue
11763 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
11764   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11765   SDValue V1 = SVOp->getOperand(0);
11766   SDValue V2 = SVOp->getOperand(1);
11767   SDLoc dl(SVOp);
11768
11769   if (V2.getOpcode() != ISD::UNDEF)
11770     return SDValue();
11771
11772   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11773   return getPSHUFB(MaskVals, V1, dl, DAG);
11774 }
11775
11776 // v16i8 shuffles - Prefer shuffles in the following order:
11777 // 1. [ssse3] 1 x pshufb
11778 // 2. [ssse3] 2 x pshufb + 1 x por
11779 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
11780 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
11781                                         const X86Subtarget* Subtarget,
11782                                         SelectionDAG &DAG) {
11783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11784   SDValue V1 = SVOp->getOperand(0);
11785   SDValue V2 = SVOp->getOperand(1);
11786   SDLoc dl(SVOp);
11787   ArrayRef<int> MaskVals = SVOp->getMask();
11788
11789   // Promote splats to a larger type which usually leads to more efficient code.
11790   // FIXME: Is this true if pshufb is available?
11791   if (SVOp->isSplat())
11792     return PromoteSplat(SVOp, DAG);
11793
11794   // If we have SSSE3, case 1 is generated when all result bytes come from
11795   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
11796   // present, fall back to case 3.
11797
11798   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
11799   if (Subtarget->hasSSSE3()) {
11800     SmallVector<SDValue,16> pshufbMask;
11801
11802     // If all result elements are from one input vector, then only translate
11803     // undef mask values to 0x80 (zero out result) in the pshufb mask.
11804     //
11805     // Otherwise, we have elements from both input vectors, and must zero out
11806     // elements that come from V2 in the first mask, and V1 in the second mask
11807     // so that we can OR them together.
11808     for (unsigned i = 0; i != 16; ++i) {
11809       int EltIdx = MaskVals[i];
11810       if (EltIdx < 0 || EltIdx >= 16)
11811         EltIdx = 0x80;
11812       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11813     }
11814     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
11815                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11816                                  MVT::v16i8, pshufbMask));
11817
11818     // As PSHUFB will zero elements with negative indices, it's safe to ignore
11819     // the 2nd operand if it's undefined or zero.
11820     if (V2.getOpcode() == ISD::UNDEF ||
11821         ISD::isBuildVectorAllZeros(V2.getNode()))
11822       return V1;
11823
11824     // Calculate the shuffle mask for the second input, shuffle it, and
11825     // OR it with the first shuffled input.
11826     pshufbMask.clear();
11827     for (unsigned i = 0; i != 16; ++i) {
11828       int EltIdx = MaskVals[i];
11829       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
11830       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11831     }
11832     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
11833                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11834                                  MVT::v16i8, pshufbMask));
11835     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11836   }
11837
11838   // No SSSE3 - Calculate in place words and then fix all out of place words
11839   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
11840   // the 16 different words that comprise the two doublequadword input vectors.
11841   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11842   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
11843   SDValue NewV = V1;
11844   for (int i = 0; i != 8; ++i) {
11845     int Elt0 = MaskVals[i*2];
11846     int Elt1 = MaskVals[i*2+1];
11847
11848     // This word of the result is all undef, skip it.
11849     if (Elt0 < 0 && Elt1 < 0)
11850       continue;
11851
11852     // This word of the result is already in the correct place, skip it.
11853     if ((Elt0 == i*2) && (Elt1 == i*2+1))
11854       continue;
11855
11856     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
11857     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
11858     SDValue InsElt;
11859
11860     // If Elt0 and Elt1 are defined, are consecutive, and can be load
11861     // using a single extract together, load it and store it.
11862     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
11863       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11864                            DAG.getIntPtrConstant(Elt1 / 2));
11865       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11866                         DAG.getIntPtrConstant(i));
11867       continue;
11868     }
11869
11870     // If Elt1 is defined, extract it from the appropriate source.  If the
11871     // source byte is not also odd, shift the extracted word left 8 bits
11872     // otherwise clear the bottom 8 bits if we need to do an or.
11873     if (Elt1 >= 0) {
11874       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11875                            DAG.getIntPtrConstant(Elt1 / 2));
11876       if ((Elt1 & 1) == 0)
11877         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
11878                              DAG.getConstant(8,
11879                                   TLI.getShiftAmountTy(InsElt.getValueType())));
11880       else if (Elt0 >= 0)
11881         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
11882                              DAG.getConstant(0xFF00, MVT::i16));
11883     }
11884     // If Elt0 is defined, extract it from the appropriate source.  If the
11885     // source byte is not also even, shift the extracted word right 8 bits. If
11886     // Elt1 was also defined, OR the extracted values together before
11887     // inserting them in the result.
11888     if (Elt0 >= 0) {
11889       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
11890                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
11891       if ((Elt0 & 1) != 0)
11892         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
11893                               DAG.getConstant(8,
11894                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
11895       else if (Elt1 >= 0)
11896         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
11897                              DAG.getConstant(0x00FF, MVT::i16));
11898       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
11899                          : InsElt0;
11900     }
11901     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11902                        DAG.getIntPtrConstant(i));
11903   }
11904   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
11905 }
11906
11907 // v32i8 shuffles - Translate to VPSHUFB if possible.
11908 static
11909 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
11910                                  const X86Subtarget *Subtarget,
11911                                  SelectionDAG &DAG) {
11912   MVT VT = SVOp->getSimpleValueType(0);
11913   SDValue V1 = SVOp->getOperand(0);
11914   SDValue V2 = SVOp->getOperand(1);
11915   SDLoc dl(SVOp);
11916   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11917
11918   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11919   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
11920   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
11921
11922   // VPSHUFB may be generated if
11923   // (1) one of input vector is undefined or zeroinitializer.
11924   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
11925   // And (2) the mask indexes don't cross the 128-bit lane.
11926   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
11927       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
11928     return SDValue();
11929
11930   if (V1IsAllZero && !V2IsAllZero) {
11931     CommuteVectorShuffleMask(MaskVals, 32);
11932     V1 = V2;
11933   }
11934   return getPSHUFB(MaskVals, V1, dl, DAG);
11935 }
11936
11937 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
11938 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
11939 /// done when every pair / quad of shuffle mask elements point to elements in
11940 /// the right sequence. e.g.
11941 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
11942 static
11943 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
11944                                  SelectionDAG &DAG) {
11945   MVT VT = SVOp->getSimpleValueType(0);
11946   SDLoc dl(SVOp);
11947   unsigned NumElems = VT.getVectorNumElements();
11948   MVT NewVT;
11949   unsigned Scale;
11950   switch (VT.SimpleTy) {
11951   default: llvm_unreachable("Unexpected!");
11952   case MVT::v2i64:
11953   case MVT::v2f64:
11954            return SDValue(SVOp, 0);
11955   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
11956   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
11957   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
11958   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
11959   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
11960   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
11961   }
11962
11963   SmallVector<int, 8> MaskVec;
11964   for (unsigned i = 0; i != NumElems; i += Scale) {
11965     int StartIdx = -1;
11966     for (unsigned j = 0; j != Scale; ++j) {
11967       int EltIdx = SVOp->getMaskElt(i+j);
11968       if (EltIdx < 0)
11969         continue;
11970       if (StartIdx < 0)
11971         StartIdx = (EltIdx / Scale);
11972       if (EltIdx != (int)(StartIdx*Scale + j))
11973         return SDValue();
11974     }
11975     MaskVec.push_back(StartIdx);
11976   }
11977
11978   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
11979   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
11980   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
11981 }
11982
11983 /// getVZextMovL - Return a zero-extending vector move low node.
11984 ///
11985 static SDValue getVZextMovL(MVT VT, MVT OpVT,
11986                             SDValue SrcOp, SelectionDAG &DAG,
11987                             const X86Subtarget *Subtarget, SDLoc dl) {
11988   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
11989     LoadSDNode *LD = nullptr;
11990     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
11991       LD = dyn_cast<LoadSDNode>(SrcOp);
11992     if (!LD) {
11993       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
11994       // instead.
11995       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
11996       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
11997           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11998           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
11999           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
12000         // PR2108
12001         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
12002         return DAG.getNode(ISD::BITCAST, dl, VT,
12003                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
12004                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
12005                                                    OpVT,
12006                                                    SrcOp.getOperand(0)
12007                                                           .getOperand(0))));
12008       }
12009     }
12010   }
12011
12012   return DAG.getNode(ISD::BITCAST, dl, VT,
12013                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
12014                                  DAG.getNode(ISD::BITCAST, dl,
12015                                              OpVT, SrcOp)));
12016 }
12017
12018 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
12019 /// which could not be matched by any known target speficic shuffle
12020 static SDValue
12021 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
12022
12023   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
12024   if (NewOp.getNode())
12025     return NewOp;
12026
12027   MVT VT = SVOp->getSimpleValueType(0);
12028
12029   unsigned NumElems = VT.getVectorNumElements();
12030   unsigned NumLaneElems = NumElems / 2;
12031
12032   SDLoc dl(SVOp);
12033   MVT EltVT = VT.getVectorElementType();
12034   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
12035   SDValue Output[2];
12036
12037   SmallVector<int, 16> Mask;
12038   for (unsigned l = 0; l < 2; ++l) {
12039     // Build a shuffle mask for the output, discovering on the fly which
12040     // input vectors to use as shuffle operands (recorded in InputUsed).
12041     // If building a suitable shuffle vector proves too hard, then bail
12042     // out with UseBuildVector set.
12043     bool UseBuildVector = false;
12044     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
12045     unsigned LaneStart = l * NumLaneElems;
12046     for (unsigned i = 0; i != NumLaneElems; ++i) {
12047       // The mask element.  This indexes into the input.
12048       int Idx = SVOp->getMaskElt(i+LaneStart);
12049       if (Idx < 0) {
12050         // the mask element does not index into any input vector.
12051         Mask.push_back(-1);
12052         continue;
12053       }
12054
12055       // The input vector this mask element indexes into.
12056       int Input = Idx / NumLaneElems;
12057
12058       // Turn the index into an offset from the start of the input vector.
12059       Idx -= Input * NumLaneElems;
12060
12061       // Find or create a shuffle vector operand to hold this input.
12062       unsigned OpNo;
12063       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
12064         if (InputUsed[OpNo] == Input)
12065           // This input vector is already an operand.
12066           break;
12067         if (InputUsed[OpNo] < 0) {
12068           // Create a new operand for this input vector.
12069           InputUsed[OpNo] = Input;
12070           break;
12071         }
12072       }
12073
12074       if (OpNo >= array_lengthof(InputUsed)) {
12075         // More than two input vectors used!  Give up on trying to create a
12076         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
12077         UseBuildVector = true;
12078         break;
12079       }
12080
12081       // Add the mask index for the new shuffle vector.
12082       Mask.push_back(Idx + OpNo * NumLaneElems);
12083     }
12084
12085     if (UseBuildVector) {
12086       SmallVector<SDValue, 16> SVOps;
12087       for (unsigned i = 0; i != NumLaneElems; ++i) {
12088         // The mask element.  This indexes into the input.
12089         int Idx = SVOp->getMaskElt(i+LaneStart);
12090         if (Idx < 0) {
12091           SVOps.push_back(DAG.getUNDEF(EltVT));
12092           continue;
12093         }
12094
12095         // The input vector this mask element indexes into.
12096         int Input = Idx / NumElems;
12097
12098         // Turn the index into an offset from the start of the input vector.
12099         Idx -= Input * NumElems;
12100
12101         // Extract the vector element by hand.
12102         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
12103                                     SVOp->getOperand(Input),
12104                                     DAG.getIntPtrConstant(Idx)));
12105       }
12106
12107       // Construct the output using a BUILD_VECTOR.
12108       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
12109     } else if (InputUsed[0] < 0) {
12110       // No input vectors were used! The result is undefined.
12111       Output[l] = DAG.getUNDEF(NVT);
12112     } else {
12113       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
12114                                         (InputUsed[0] % 2) * NumLaneElems,
12115                                         DAG, dl);
12116       // If only one input was used, use an undefined vector for the other.
12117       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
12118         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
12119                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
12120       // At least one input vector was used. Create a new shuffle vector.
12121       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
12122     }
12123
12124     Mask.clear();
12125   }
12126
12127   // Concatenate the result back
12128   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
12129 }
12130
12131 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
12132 /// 4 elements, and match them with several different shuffle types.
12133 static SDValue
12134 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
12135   SDValue V1 = SVOp->getOperand(0);
12136   SDValue V2 = SVOp->getOperand(1);
12137   SDLoc dl(SVOp);
12138   MVT VT = SVOp->getSimpleValueType(0);
12139
12140   assert(VT.is128BitVector() && "Unsupported vector size");
12141
12142   std::pair<int, int> Locs[4];
12143   int Mask1[] = { -1, -1, -1, -1 };
12144   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
12145
12146   unsigned NumHi = 0;
12147   unsigned NumLo = 0;
12148   for (unsigned i = 0; i != 4; ++i) {
12149     int Idx = PermMask[i];
12150     if (Idx < 0) {
12151       Locs[i] = std::make_pair(-1, -1);
12152     } else {
12153       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
12154       if (Idx < 4) {
12155         Locs[i] = std::make_pair(0, NumLo);
12156         Mask1[NumLo] = Idx;
12157         NumLo++;
12158       } else {
12159         Locs[i] = std::make_pair(1, NumHi);
12160         if (2+NumHi < 4)
12161           Mask1[2+NumHi] = Idx;
12162         NumHi++;
12163       }
12164     }
12165   }
12166
12167   if (NumLo <= 2 && NumHi <= 2) {
12168     // If no more than two elements come from either vector. This can be
12169     // implemented with two shuffles. First shuffle gather the elements.
12170     // The second shuffle, which takes the first shuffle as both of its
12171     // vector operands, put the elements into the right order.
12172     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
12173
12174     int Mask2[] = { -1, -1, -1, -1 };
12175
12176     for (unsigned i = 0; i != 4; ++i)
12177       if (Locs[i].first != -1) {
12178         unsigned Idx = (i < 2) ? 0 : 4;
12179         Idx += Locs[i].first * 2 + Locs[i].second;
12180         Mask2[i] = Idx;
12181       }
12182
12183     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
12184   }
12185
12186   if (NumLo == 3 || NumHi == 3) {
12187     // Otherwise, we must have three elements from one vector, call it X, and
12188     // one element from the other, call it Y.  First, use a shufps to build an
12189     // intermediate vector with the one element from Y and the element from X
12190     // that will be in the same half in the final destination (the indexes don't
12191     // matter). Then, use a shufps to build the final vector, taking the half
12192     // containing the element from Y from the intermediate, and the other half
12193     // from X.
12194     if (NumHi == 3) {
12195       // Normalize it so the 3 elements come from V1.
12196       CommuteVectorShuffleMask(PermMask, 4);
12197       std::swap(V1, V2);
12198     }
12199
12200     // Find the element from V2.
12201     unsigned HiIndex;
12202     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
12203       int Val = PermMask[HiIndex];
12204       if (Val < 0)
12205         continue;
12206       if (Val >= 4)
12207         break;
12208     }
12209
12210     Mask1[0] = PermMask[HiIndex];
12211     Mask1[1] = -1;
12212     Mask1[2] = PermMask[HiIndex^1];
12213     Mask1[3] = -1;
12214     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
12215
12216     if (HiIndex >= 2) {
12217       Mask1[0] = PermMask[0];
12218       Mask1[1] = PermMask[1];
12219       Mask1[2] = HiIndex & 1 ? 6 : 4;
12220       Mask1[3] = HiIndex & 1 ? 4 : 6;
12221       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
12222     }
12223
12224     Mask1[0] = HiIndex & 1 ? 2 : 0;
12225     Mask1[1] = HiIndex & 1 ? 0 : 2;
12226     Mask1[2] = PermMask[2];
12227     Mask1[3] = PermMask[3];
12228     if (Mask1[2] >= 0)
12229       Mask1[2] += 4;
12230     if (Mask1[3] >= 0)
12231       Mask1[3] += 4;
12232     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
12233   }
12234
12235   // Break it into (shuffle shuffle_hi, shuffle_lo).
12236   int LoMask[] = { -1, -1, -1, -1 };
12237   int HiMask[] = { -1, -1, -1, -1 };
12238
12239   int *MaskPtr = LoMask;
12240   unsigned MaskIdx = 0;
12241   unsigned LoIdx = 0;
12242   unsigned HiIdx = 2;
12243   for (unsigned i = 0; i != 4; ++i) {
12244     if (i == 2) {
12245       MaskPtr = HiMask;
12246       MaskIdx = 1;
12247       LoIdx = 0;
12248       HiIdx = 2;
12249     }
12250     int Idx = PermMask[i];
12251     if (Idx < 0) {
12252       Locs[i] = std::make_pair(-1, -1);
12253     } else if (Idx < 4) {
12254       Locs[i] = std::make_pair(MaskIdx, LoIdx);
12255       MaskPtr[LoIdx] = Idx;
12256       LoIdx++;
12257     } else {
12258       Locs[i] = std::make_pair(MaskIdx, HiIdx);
12259       MaskPtr[HiIdx] = Idx;
12260       HiIdx++;
12261     }
12262   }
12263
12264   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
12265   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
12266   int MaskOps[] = { -1, -1, -1, -1 };
12267   for (unsigned i = 0; i != 4; ++i)
12268     if (Locs[i].first != -1)
12269       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
12270   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
12271 }
12272
12273 static bool MayFoldVectorLoad(SDValue V) {
12274   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
12275     V = V.getOperand(0);
12276
12277   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
12278     V = V.getOperand(0);
12279   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
12280       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
12281     // BUILD_VECTOR (load), undef
12282     V = V.getOperand(0);
12283
12284   return MayFoldLoad(V);
12285 }
12286
12287 static
12288 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
12289   MVT VT = Op.getSimpleValueType();
12290
12291   // Canonicalize to v2f64.
12292   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
12293   return DAG.getNode(ISD::BITCAST, dl, VT,
12294                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
12295                                           V1, DAG));
12296 }
12297
12298 static
12299 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
12300                         bool HasSSE2) {
12301   SDValue V1 = Op.getOperand(0);
12302   SDValue V2 = Op.getOperand(1);
12303   MVT VT = Op.getSimpleValueType();
12304
12305   assert(VT != MVT::v2i64 && "unsupported shuffle type");
12306
12307   if (HasSSE2 && VT == MVT::v2f64)
12308     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
12309
12310   // v4f32 or v4i32: canonicalize to v4f32 (which is legal for SSE1)
12311   return DAG.getNode(ISD::BITCAST, dl, VT,
12312                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
12313                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
12314                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
12315 }
12316
12317 static
12318 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
12319   SDValue V1 = Op.getOperand(0);
12320   SDValue V2 = Op.getOperand(1);
12321   MVT VT = Op.getSimpleValueType();
12322
12323   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
12324          "unsupported shuffle type");
12325
12326   if (V2.getOpcode() == ISD::UNDEF)
12327     V2 = V1;
12328
12329   // v4i32 or v4f32
12330   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
12331 }
12332
12333 static
12334 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
12335   SDValue V1 = Op.getOperand(0);
12336   SDValue V2 = Op.getOperand(1);
12337   MVT VT = Op.getSimpleValueType();
12338   unsigned NumElems = VT.getVectorNumElements();
12339
12340   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
12341   // operand of these instructions is only memory, so check if there's a
12342   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
12343   // same masks.
12344   bool CanFoldLoad = false;
12345
12346   // Trivial case, when V2 comes from a load.
12347   if (MayFoldVectorLoad(V2))
12348     CanFoldLoad = true;
12349
12350   // When V1 is a load, it can be folded later into a store in isel, example:
12351   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
12352   //    turns into:
12353   //  (MOVLPSmr addr:$src1, VR128:$src2)
12354   // So, recognize this potential and also use MOVLPS or MOVLPD
12355   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
12356     CanFoldLoad = true;
12357
12358   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12359   if (CanFoldLoad) {
12360     if (HasSSE2 && NumElems == 2)
12361       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
12362
12363     if (NumElems == 4)
12364       // If we don't care about the second element, proceed to use movss.
12365       if (SVOp->getMaskElt(1) != -1)
12366         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
12367   }
12368
12369   // movl and movlp will both match v2i64, but v2i64 is never matched by
12370   // movl earlier because we make it strict to avoid messing with the movlp load
12371   // folding logic (see the code above getMOVLP call). Match it here then,
12372   // this is horrible, but will stay like this until we move all shuffle
12373   // matching to x86 specific nodes. Note that for the 1st condition all
12374   // types are matched with movsd.
12375   if (HasSSE2) {
12376     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
12377     // as to remove this logic from here, as much as possible
12378     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
12379       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
12380     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
12381   }
12382
12383   assert(VT != MVT::v4i32 && "unsupported shuffle type");
12384
12385   // Invert the operand order and use SHUFPS to match it.
12386   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
12387                               getShuffleSHUFImmediate(SVOp), DAG);
12388 }
12389
12390 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
12391                                          SelectionDAG &DAG) {
12392   SDLoc dl(Load);
12393   MVT VT = Load->getSimpleValueType(0);
12394   MVT EVT = VT.getVectorElementType();
12395   SDValue Addr = Load->getOperand(1);
12396   SDValue NewAddr = DAG.getNode(
12397       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
12398       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
12399
12400   SDValue NewLoad =
12401       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
12402                   DAG.getMachineFunction().getMachineMemOperand(
12403                       Load->getMemOperand(), 0, EVT.getStoreSize()));
12404   return NewLoad;
12405 }
12406
12407 // It is only safe to call this function if isINSERTPSMask is true for
12408 // this shufflevector mask.
12409 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
12410                            SelectionDAG &DAG) {
12411   // Generate an insertps instruction when inserting an f32 from memory onto a
12412   // v4f32 or when copying a member from one v4f32 to another.
12413   // We also use it for transferring i32 from one register to another,
12414   // since it simply copies the same bits.
12415   // If we're transferring an i32 from memory to a specific element in a
12416   // register, we output a generic DAG that will match the PINSRD
12417   // instruction.
12418   MVT VT = SVOp->getSimpleValueType(0);
12419   MVT EVT = VT.getVectorElementType();
12420   SDValue V1 = SVOp->getOperand(0);
12421   SDValue V2 = SVOp->getOperand(1);
12422   auto Mask = SVOp->getMask();
12423   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
12424          "unsupported vector type for insertps/pinsrd");
12425
12426   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
12427   auto FromV2Predicate = [](const int &i) { return i >= 4; };
12428   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
12429
12430   SDValue From;
12431   SDValue To;
12432   unsigned DestIndex;
12433   if (FromV1 == 1) {
12434     From = V1;
12435     To = V2;
12436     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
12437                 Mask.begin();
12438
12439     // If we have 1 element from each vector, we have to check if we're
12440     // changing V1's element's place. If so, we're done. Otherwise, we
12441     // should assume we're changing V2's element's place and behave
12442     // accordingly.
12443     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
12444     assert(DestIndex <= INT32_MAX && "truncated destination index");
12445     if (FromV1 == FromV2 &&
12446         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
12447       From = V2;
12448       To = V1;
12449       DestIndex =
12450           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
12451     }
12452   } else {
12453     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
12454            "More than one element from V1 and from V2, or no elements from one "
12455            "of the vectors. This case should not have returned true from "
12456            "isINSERTPSMask");
12457     From = V2;
12458     To = V1;
12459     DestIndex =
12460         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
12461   }
12462
12463   // Get an index into the source vector in the range [0,4) (the mask is
12464   // in the range [0,8) because it can address V1 and V2)
12465   unsigned SrcIndex = Mask[DestIndex] % 4;
12466   if (MayFoldLoad(From)) {
12467     // Trivial case, when From comes from a load and is only used by the
12468     // shuffle. Make it use insertps from the vector that we need from that
12469     // load.
12470     SDValue NewLoad =
12471         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
12472     if (!NewLoad.getNode())
12473       return SDValue();
12474
12475     if (EVT == MVT::f32) {
12476       // Create this as a scalar to vector to match the instruction pattern.
12477       SDValue LoadScalarToVector =
12478           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
12479       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
12480       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
12481                          InsertpsMask);
12482     } else { // EVT == MVT::i32
12483       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
12484       // instruction, to match the PINSRD instruction, which loads an i32 to a
12485       // certain vector element.
12486       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
12487                          DAG.getConstant(DestIndex, MVT::i32));
12488     }
12489   }
12490
12491   // Vector-element-to-vector
12492   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
12493   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
12494 }
12495
12496 // Reduce a vector shuffle to zext.
12497 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
12498                                     SelectionDAG &DAG) {
12499   // PMOVZX is only available from SSE41.
12500   if (!Subtarget->hasSSE41())
12501     return SDValue();
12502
12503   MVT VT = Op.getSimpleValueType();
12504
12505   // Only AVX2 support 256-bit vector integer extending.
12506   if (!Subtarget->hasInt256() && VT.is256BitVector())
12507     return SDValue();
12508
12509   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12510   SDLoc DL(Op);
12511   SDValue V1 = Op.getOperand(0);
12512   SDValue V2 = Op.getOperand(1);
12513   unsigned NumElems = VT.getVectorNumElements();
12514
12515   // Extending is an unary operation and the element type of the source vector
12516   // won't be equal to or larger than i64.
12517   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
12518       VT.getVectorElementType() == MVT::i64)
12519     return SDValue();
12520
12521   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
12522   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
12523   while ((1U << Shift) < NumElems) {
12524     if (SVOp->getMaskElt(1U << Shift) == 1)
12525       break;
12526     Shift += 1;
12527     // The maximal ratio is 8, i.e. from i8 to i64.
12528     if (Shift > 3)
12529       return SDValue();
12530   }
12531
12532   // Check the shuffle mask.
12533   unsigned Mask = (1U << Shift) - 1;
12534   for (unsigned i = 0; i != NumElems; ++i) {
12535     int EltIdx = SVOp->getMaskElt(i);
12536     if ((i & Mask) != 0 && EltIdx != -1)
12537       return SDValue();
12538     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
12539       return SDValue();
12540   }
12541
12542   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
12543   MVT NeVT = MVT::getIntegerVT(NBits);
12544   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
12545
12546   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
12547     return SDValue();
12548
12549   return DAG.getNode(ISD::BITCAST, DL, VT,
12550                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
12551 }
12552
12553 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
12554                                       SelectionDAG &DAG) {
12555   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12556   MVT VT = Op.getSimpleValueType();
12557   SDLoc dl(Op);
12558   SDValue V1 = Op.getOperand(0);
12559   SDValue V2 = Op.getOperand(1);
12560
12561   if (isZeroShuffle(SVOp))
12562     return getZeroVector(VT, Subtarget, DAG, dl);
12563
12564   // Handle splat operations
12565   if (SVOp->isSplat()) {
12566     // Use vbroadcast whenever the splat comes from a foldable load
12567     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
12568     if (Broadcast.getNode())
12569       return Broadcast;
12570   }
12571
12572   // Check integer expanding shuffles.
12573   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
12574   if (NewOp.getNode())
12575     return NewOp;
12576
12577   // If the shuffle can be profitably rewritten as a narrower shuffle, then
12578   // do it!
12579   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
12580       VT == MVT::v32i8) {
12581     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12582     if (NewOp.getNode())
12583       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
12584   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
12585     // FIXME: Figure out a cleaner way to do this.
12586     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
12587       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12588       if (NewOp.getNode()) {
12589         MVT NewVT = NewOp.getSimpleValueType();
12590         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
12591                                NewVT, true, false))
12592           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
12593                               dl);
12594       }
12595     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
12596       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12597       if (NewOp.getNode()) {
12598         MVT NewVT = NewOp.getSimpleValueType();
12599         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
12600           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
12601                               dl);
12602       }
12603     }
12604   }
12605   return SDValue();
12606 }
12607
12608 SDValue
12609 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
12610   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12611   SDValue V1 = Op.getOperand(0);
12612   SDValue V2 = Op.getOperand(1);
12613   MVT VT = Op.getSimpleValueType();
12614   SDLoc dl(Op);
12615   unsigned NumElems = VT.getVectorNumElements();
12616   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
12617   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
12618   bool V1IsSplat = false;
12619   bool V2IsSplat = false;
12620   bool HasSSE2 = Subtarget->hasSSE2();
12621   bool HasFp256    = Subtarget->hasFp256();
12622   bool HasInt256   = Subtarget->hasInt256();
12623   MachineFunction &MF = DAG.getMachineFunction();
12624   bool OptForSize =
12625       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
12626
12627   // Check if we should use the experimental vector shuffle lowering. If so,
12628   // delegate completely to that code path.
12629   if (ExperimentalVectorShuffleLowering)
12630     return lowerVectorShuffle(Op, Subtarget, DAG);
12631
12632   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
12633
12634   if (V1IsUndef && V2IsUndef)
12635     return DAG.getUNDEF(VT);
12636
12637   // When we create a shuffle node we put the UNDEF node to second operand,
12638   // but in some cases the first operand may be transformed to UNDEF.
12639   // In this case we should just commute the node.
12640   if (V1IsUndef)
12641     return DAG.getCommutedVectorShuffle(*SVOp);
12642
12643   // Vector shuffle lowering takes 3 steps:
12644   //
12645   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
12646   //    narrowing and commutation of operands should be handled.
12647   // 2) Matching of shuffles with known shuffle masks to x86 target specific
12648   //    shuffle nodes.
12649   // 3) Rewriting of unmatched masks into new generic shuffle operations,
12650   //    so the shuffle can be broken into other shuffles and the legalizer can
12651   //    try the lowering again.
12652   //
12653   // The general idea is that no vector_shuffle operation should be left to
12654   // be matched during isel, all of them must be converted to a target specific
12655   // node here.
12656
12657   // Normalize the input vectors. Here splats, zeroed vectors, profitable
12658   // narrowing and commutation of operands should be handled. The actual code
12659   // doesn't include all of those, work in progress...
12660   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
12661   if (NewOp.getNode())
12662     return NewOp;
12663
12664   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
12665
12666   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
12667   // unpckh_undef). Only use pshufd if speed is more important than size.
12668   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12669     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12670   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12671     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12672
12673   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
12674       V2IsUndef && MayFoldVectorLoad(V1))
12675     return getMOVDDup(Op, dl, V1, DAG);
12676
12677   if (isMOVHLPS_v_undef_Mask(M, VT))
12678     return getMOVHighToLow(Op, dl, DAG);
12679
12680   // Use to match splats
12681   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
12682       (VT == MVT::v2f64 || VT == MVT::v2i64))
12683     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12684
12685   if (isPSHUFDMask(M, VT)) {
12686     // The actual implementation will match the mask in the if above and then
12687     // during isel it can match several different instructions, not only pshufd
12688     // as its name says, sad but true, emulate the behavior for now...
12689     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
12690       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
12691
12692     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
12693
12694     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
12695       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
12696
12697     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
12698       return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1, TargetMask,
12699                                   DAG);
12700
12701     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
12702                                 TargetMask, DAG);
12703   }
12704
12705   if (isPALIGNRMask(M, VT, Subtarget))
12706     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
12707                                 getShufflePALIGNRImmediate(SVOp),
12708                                 DAG);
12709
12710   if (isVALIGNMask(M, VT, Subtarget))
12711     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
12712                                 getShuffleVALIGNImmediate(SVOp),
12713                                 DAG);
12714
12715   // Check if this can be converted into a logical shift.
12716   bool isLeft = false;
12717   unsigned ShAmt = 0;
12718   SDValue ShVal;
12719   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
12720   if (isShift && ShVal.hasOneUse()) {
12721     // If the shifted value has multiple uses, it may be cheaper to use
12722     // v_set0 + movlhps or movhlps, etc.
12723     MVT EltVT = VT.getVectorElementType();
12724     ShAmt *= EltVT.getSizeInBits();
12725     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12726   }
12727
12728   if (isMOVLMask(M, VT)) {
12729     if (ISD::isBuildVectorAllZeros(V1.getNode()))
12730       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
12731     if (!isMOVLPMask(M, VT)) {
12732       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
12733         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
12734
12735       if (VT == MVT::v4i32 || VT == MVT::v4f32)
12736         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
12737     }
12738   }
12739
12740   // FIXME: fold these into legal mask.
12741   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
12742     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
12743
12744   if (isMOVHLPSMask(M, VT))
12745     return getMOVHighToLow(Op, dl, DAG);
12746
12747   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
12748     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
12749
12750   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
12751     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
12752
12753   if (isMOVLPMask(M, VT))
12754     return getMOVLP(Op, dl, DAG, HasSSE2);
12755
12756   if (ShouldXformToMOVHLPS(M, VT) ||
12757       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
12758     return DAG.getCommutedVectorShuffle(*SVOp);
12759
12760   if (isShift) {
12761     // No better options. Use a vshldq / vsrldq.
12762     MVT EltVT = VT.getVectorElementType();
12763     ShAmt *= EltVT.getSizeInBits();
12764     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12765   }
12766
12767   bool Commuted = false;
12768   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
12769   // 1,1,1,1 -> v8i16 though.
12770   BitVector UndefElements;
12771   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
12772     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12773       V1IsSplat = true;
12774   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
12775     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12776       V2IsSplat = true;
12777
12778   // Canonicalize the splat or undef, if present, to be on the RHS.
12779   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
12780     CommuteVectorShuffleMask(M, NumElems);
12781     std::swap(V1, V2);
12782     std::swap(V1IsSplat, V2IsSplat);
12783     Commuted = true;
12784   }
12785
12786   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
12787     // Shuffling low element of v1 into undef, just return v1.
12788     if (V2IsUndef)
12789       return V1;
12790     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
12791     // the instruction selector will not match, so get a canonical MOVL with
12792     // swapped operands to undo the commute.
12793     return getMOVL(DAG, dl, VT, V2, V1);
12794   }
12795
12796   if (isUNPCKLMask(M, VT, HasInt256))
12797     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12798
12799   if (isUNPCKHMask(M, VT, HasInt256))
12800     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12801
12802   if (V2IsSplat) {
12803     // Normalize mask so all entries that point to V2 points to its first
12804     // element then try to match unpck{h|l} again. If match, return a
12805     // new vector_shuffle with the corrected mask.p
12806     SmallVector<int, 8> NewMask(M.begin(), M.end());
12807     NormalizeMask(NewMask, NumElems);
12808     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
12809       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12810     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
12811       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12812   }
12813
12814   if (Commuted) {
12815     // Commute is back and try unpck* again.
12816     // FIXME: this seems wrong.
12817     CommuteVectorShuffleMask(M, NumElems);
12818     std::swap(V1, V2);
12819     std::swap(V1IsSplat, V2IsSplat);
12820
12821     if (isUNPCKLMask(M, VT, HasInt256))
12822       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12823
12824     if (isUNPCKHMask(M, VT, HasInt256))
12825       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12826   }
12827
12828   // Normalize the node to match x86 shuffle ops if needed
12829   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
12830     return DAG.getCommutedVectorShuffle(*SVOp);
12831
12832   // The checks below are all present in isShuffleMaskLegal, but they are
12833   // inlined here right now to enable us to directly emit target specific
12834   // nodes, and remove one by one until they don't return Op anymore.
12835
12836   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
12837       SVOp->getSplatIndex() == 0 && V2IsUndef) {
12838     if (VT == MVT::v2f64 || VT == MVT::v2i64)
12839       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12840   }
12841
12842   if (isPSHUFHWMask(M, VT, HasInt256))
12843     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
12844                                 getShufflePSHUFHWImmediate(SVOp),
12845                                 DAG);
12846
12847   if (isPSHUFLWMask(M, VT, HasInt256))
12848     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
12849                                 getShufflePSHUFLWImmediate(SVOp),
12850                                 DAG);
12851
12852   unsigned MaskValue;
12853   if (isBlendMask(M, VT, Subtarget->hasSSE41(), HasInt256, &MaskValue))
12854     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
12855
12856   if (isSHUFPMask(M, VT))
12857     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
12858                                 getShuffleSHUFImmediate(SVOp), DAG);
12859
12860   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12861     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12862   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12863     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12864
12865   //===--------------------------------------------------------------------===//
12866   // Generate target specific nodes for 128 or 256-bit shuffles only
12867   // supported in the AVX instruction set.
12868   //
12869
12870   // Handle VMOVDDUPY permutations
12871   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
12872     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
12873
12874   // Handle VPERMILPS/D* permutations
12875   if (isVPERMILPMask(M, VT)) {
12876     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
12877       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
12878                                   getShuffleSHUFImmediate(SVOp), DAG);
12879     return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1,
12880                                 getShuffleSHUFImmediate(SVOp), DAG);
12881   }
12882
12883   unsigned Idx;
12884   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
12885     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
12886                               Idx*(NumElems/2), DAG, dl);
12887
12888   // Handle VPERM2F128/VPERM2I128 permutations
12889   if (isVPERM2X128Mask(M, VT, HasFp256))
12890     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
12891                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
12892
12893   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
12894     return getINSERTPS(SVOp, dl, DAG);
12895
12896   unsigned Imm8;
12897   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
12898     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
12899
12900   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
12901       VT.is512BitVector()) {
12902     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
12903     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
12904     SmallVector<SDValue, 16> permclMask;
12905     for (unsigned i = 0; i != NumElems; ++i) {
12906       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
12907     }
12908
12909     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
12910     if (V2IsUndef)
12911       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
12912       return DAG.getNode(X86ISD::VPERMV, dl, VT,
12913                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
12914     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
12915                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
12916   }
12917
12918   //===--------------------------------------------------------------------===//
12919   // Since no target specific shuffle was selected for this generic one,
12920   // lower it into other known shuffles. FIXME: this isn't true yet, but
12921   // this is the plan.
12922   //
12923
12924   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
12925   if (VT == MVT::v8i16) {
12926     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
12927     if (NewOp.getNode())
12928       return NewOp;
12929   }
12930
12931   if (VT == MVT::v16i16 && HasInt256) {
12932     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
12933     if (NewOp.getNode())
12934       return NewOp;
12935   }
12936
12937   if (VT == MVT::v16i8) {
12938     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
12939     if (NewOp.getNode())
12940       return NewOp;
12941   }
12942
12943   if (VT == MVT::v32i8) {
12944     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
12945     if (NewOp.getNode())
12946       return NewOp;
12947   }
12948
12949   // Handle all 128-bit wide vectors with 4 elements, and match them with
12950   // several different shuffle types.
12951   if (NumElems == 4 && VT.is128BitVector())
12952     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
12953
12954   // Handle general 256-bit shuffles
12955   if (VT.is256BitVector())
12956     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
12957
12958   return SDValue();
12959 }
12960
12961 // This function assumes its argument is a BUILD_VECTOR of constants or
12962 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
12963 // true.
12964 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
12965                                     unsigned &MaskValue) {
12966   MaskValue = 0;
12967   unsigned NumElems = BuildVector->getNumOperands();
12968   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
12969   unsigned NumLanes = (NumElems - 1) / 8 + 1;
12970   unsigned NumElemsInLane = NumElems / NumLanes;
12971
12972   // Blend for v16i16 should be symetric for the both lanes.
12973   for (unsigned i = 0; i < NumElemsInLane; ++i) {
12974     SDValue EltCond = BuildVector->getOperand(i);
12975     SDValue SndLaneEltCond =
12976         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
12977
12978     int Lane1Cond = -1, Lane2Cond = -1;
12979     if (isa<ConstantSDNode>(EltCond))
12980       Lane1Cond = !isZero(EltCond);
12981     if (isa<ConstantSDNode>(SndLaneEltCond))
12982       Lane2Cond = !isZero(SndLaneEltCond);
12983
12984     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
12985       // Lane1Cond != 0, means we want the first argument.
12986       // Lane1Cond == 0, means we want the second argument.
12987       // The encoding of this argument is 0 for the first argument, 1
12988       // for the second. Therefore, invert the condition.
12989       MaskValue |= !Lane1Cond << i;
12990     else if (Lane1Cond < 0)
12991       MaskValue |= !Lane2Cond << i;
12992     else
12993       return false;
12994   }
12995   return true;
12996 }
12997
12998 /// \brief Try to lower a VSELECT instruction to an immediate-controlled blend
12999 /// instruction.
13000 static SDValue lowerVSELECTtoBLENDI(SDValue Op, const X86Subtarget *Subtarget,
13001                                     SelectionDAG &DAG) {
13002   SDValue Cond = Op.getOperand(0);
13003   SDValue LHS = Op.getOperand(1);
13004   SDValue RHS = Op.getOperand(2);
13005   SDLoc dl(Op);
13006   MVT VT = Op.getSimpleValueType();
13007   MVT EltVT = VT.getVectorElementType();
13008   unsigned NumElems = VT.getVectorNumElements();
13009
13010   // There is no blend with immediate in AVX-512.
13011   if (VT.is512BitVector())
13012     return SDValue();
13013
13014   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
13015     return SDValue();
13016   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
13017     return SDValue();
13018
13019   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
13020     return SDValue();
13021
13022   // Check the mask for BLEND and build the value.
13023   unsigned MaskValue = 0;
13024   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
13025     return SDValue();
13026
13027   // Convert i32 vectors to floating point if it is not AVX2.
13028   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
13029   MVT BlendVT = VT;
13030   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
13031     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
13032                                NumElems);
13033     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
13034     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
13035   }
13036
13037   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
13038                             DAG.getConstant(MaskValue, MVT::i32));
13039   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
13040 }
13041
13042 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
13043   // A vselect where all conditions and data are constants can be optimized into
13044   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
13045   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
13046       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
13047       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
13048     return SDValue();
13049
13050   SDValue BlendOp = lowerVSELECTtoBLENDI(Op, Subtarget, DAG);
13051   if (BlendOp.getNode())
13052     return BlendOp;
13053
13054   // Some types for vselect were previously set to Expand, not Legal or
13055   // Custom. Return an empty SDValue so we fall-through to Expand, after
13056   // the Custom lowering phase.
13057   MVT VT = Op.getSimpleValueType();
13058   switch (VT.SimpleTy) {
13059   default:
13060     break;
13061   case MVT::v8i16:
13062   case MVT::v16i16:
13063     if (Subtarget->hasBWI() && Subtarget->hasVLX())
13064       break;
13065     return SDValue();
13066   }
13067
13068   // We couldn't create a "Blend with immediate" node.
13069   // This node should still be legal, but we'll have to emit a blendv*
13070   // instruction.
13071   return Op;
13072 }
13073
13074 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
13075   MVT VT = Op.getSimpleValueType();
13076   SDLoc dl(Op);
13077
13078   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
13079     return SDValue();
13080
13081   if (VT.getSizeInBits() == 8) {
13082     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
13083                                   Op.getOperand(0), Op.getOperand(1));
13084     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
13085                                   DAG.getValueType(VT));
13086     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
13087   }
13088
13089   if (VT.getSizeInBits() == 16) {
13090     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13091     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
13092     if (Idx == 0)
13093       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
13094                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
13095                                      DAG.getNode(ISD::BITCAST, dl,
13096                                                  MVT::v4i32,
13097                                                  Op.getOperand(0)),
13098                                      Op.getOperand(1)));
13099     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
13100                                   Op.getOperand(0), Op.getOperand(1));
13101     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
13102                                   DAG.getValueType(VT));
13103     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
13104   }
13105
13106   if (VT == MVT::f32) {
13107     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
13108     // the result back to FR32 register. It's only worth matching if the
13109     // result has a single use which is a store or a bitcast to i32.  And in
13110     // the case of a store, it's not worth it if the index is a constant 0,
13111     // because a MOVSSmr can be used instead, which is smaller and faster.
13112     if (!Op.hasOneUse())
13113       return SDValue();
13114     SDNode *User = *Op.getNode()->use_begin();
13115     if ((User->getOpcode() != ISD::STORE ||
13116          (isa<ConstantSDNode>(Op.getOperand(1)) &&
13117           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
13118         (User->getOpcode() != ISD::BITCAST ||
13119          User->getValueType(0) != MVT::i32))
13120       return SDValue();
13121     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
13122                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
13123                                               Op.getOperand(0)),
13124                                               Op.getOperand(1));
13125     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
13126   }
13127
13128   if (VT == MVT::i32 || VT == MVT::i64) {
13129     // ExtractPS/pextrq works with constant index.
13130     if (isa<ConstantSDNode>(Op.getOperand(1)))
13131       return Op;
13132   }
13133   return SDValue();
13134 }
13135
13136 /// Extract one bit from mask vector, like v16i1 or v8i1.
13137 /// AVX-512 feature.
13138 SDValue
13139 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
13140   SDValue Vec = Op.getOperand(0);
13141   SDLoc dl(Vec);
13142   MVT VecVT = Vec.getSimpleValueType();
13143   SDValue Idx = Op.getOperand(1);
13144   MVT EltVT = Op.getSimpleValueType();
13145
13146   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
13147   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
13148          "Unexpected vector type in ExtractBitFromMaskVector");
13149
13150   // variable index can't be handled in mask registers,
13151   // extend vector to VR512
13152   if (!isa<ConstantSDNode>(Idx)) {
13153     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
13154     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
13155     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13156                               ExtVT.getVectorElementType(), Ext, Idx);
13157     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
13158   }
13159
13160   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13161   const TargetRegisterClass* rc = getRegClassFor(VecVT);
13162   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
13163     rc = getRegClassFor(MVT::v16i1);
13164   unsigned MaxSift = rc->getSize()*8 - 1;
13165   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
13166                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
13167   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
13168                     DAG.getConstant(MaxSift, MVT::i8));
13169   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
13170                        DAG.getIntPtrConstant(0));
13171 }
13172
13173 SDValue
13174 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
13175                                            SelectionDAG &DAG) const {
13176   SDLoc dl(Op);
13177   SDValue Vec = Op.getOperand(0);
13178   MVT VecVT = Vec.getSimpleValueType();
13179   SDValue Idx = Op.getOperand(1);
13180
13181   if (Op.getSimpleValueType() == MVT::i1)
13182     return ExtractBitFromMaskVector(Op, DAG);
13183
13184   if (!isa<ConstantSDNode>(Idx)) {
13185     if (VecVT.is512BitVector() ||
13186         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
13187          VecVT.getVectorElementType().getSizeInBits() == 32)) {
13188
13189       MVT MaskEltVT =
13190         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
13191       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
13192                                     MaskEltVT.getSizeInBits());
13193
13194       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
13195       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
13196                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
13197                                 Idx, DAG.getConstant(0, getPointerTy()));
13198       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
13199       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
13200                         Perm, DAG.getConstant(0, getPointerTy()));
13201     }
13202     return SDValue();
13203   }
13204
13205   // If this is a 256-bit vector result, first extract the 128-bit vector and
13206   // then extract the element from the 128-bit vector.
13207   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
13208
13209     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13210     // Get the 128-bit vector.
13211     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
13212     MVT EltVT = VecVT.getVectorElementType();
13213
13214     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
13215
13216     //if (IdxVal >= NumElems/2)
13217     //  IdxVal -= NumElems/2;
13218     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
13219     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
13220                        DAG.getConstant(IdxVal, MVT::i32));
13221   }
13222
13223   assert(VecVT.is128BitVector() && "Unexpected vector length");
13224
13225   if (Subtarget->hasSSE41()) {
13226     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
13227     if (Res.getNode())
13228       return Res;
13229   }
13230
13231   MVT VT = Op.getSimpleValueType();
13232   // TODO: handle v16i8.
13233   if (VT.getSizeInBits() == 16) {
13234     SDValue Vec = Op.getOperand(0);
13235     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13236     if (Idx == 0)
13237       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
13238                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
13239                                      DAG.getNode(ISD::BITCAST, dl,
13240                                                  MVT::v4i32, Vec),
13241                                      Op.getOperand(1)));
13242     // Transform it so it match pextrw which produces a 32-bit result.
13243     MVT EltVT = MVT::i32;
13244     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
13245                                   Op.getOperand(0), Op.getOperand(1));
13246     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
13247                                   DAG.getValueType(VT));
13248     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
13249   }
13250
13251   if (VT.getSizeInBits() == 32) {
13252     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13253     if (Idx == 0)
13254       return Op;
13255
13256     // SHUFPS the element to the lowest double word, then movss.
13257     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
13258     MVT VVT = Op.getOperand(0).getSimpleValueType();
13259     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
13260                                        DAG.getUNDEF(VVT), Mask);
13261     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
13262                        DAG.getIntPtrConstant(0));
13263   }
13264
13265   if (VT.getSizeInBits() == 64) {
13266     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
13267     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
13268     //        to match extract_elt for f64.
13269     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13270     if (Idx == 0)
13271       return Op;
13272
13273     // UNPCKHPD the element to the lowest double word, then movsd.
13274     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
13275     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
13276     int Mask[2] = { 1, -1 };
13277     MVT VVT = Op.getOperand(0).getSimpleValueType();
13278     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
13279                                        DAG.getUNDEF(VVT), Mask);
13280     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
13281                        DAG.getIntPtrConstant(0));
13282   }
13283
13284   return SDValue();
13285 }
13286
13287 /// Insert one bit to mask vector, like v16i1 or v8i1.
13288 /// AVX-512 feature.
13289 SDValue
13290 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
13291   SDLoc dl(Op);
13292   SDValue Vec = Op.getOperand(0);
13293   SDValue Elt = Op.getOperand(1);
13294   SDValue Idx = Op.getOperand(2);
13295   MVT VecVT = Vec.getSimpleValueType();
13296
13297   if (!isa<ConstantSDNode>(Idx)) {
13298     // Non constant index. Extend source and destination,
13299     // insert element and then truncate the result.
13300     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
13301     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
13302     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
13303       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
13304       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
13305     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
13306   }
13307
13308   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13309   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
13310   if (Vec.getOpcode() == ISD::UNDEF)
13311     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
13312                        DAG.getConstant(IdxVal, MVT::i8));
13313   const TargetRegisterClass* rc = getRegClassFor(VecVT);
13314   unsigned MaxSift = rc->getSize()*8 - 1;
13315   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
13316                     DAG.getConstant(MaxSift, MVT::i8));
13317   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
13318                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
13319   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
13320 }
13321
13322 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
13323                                                   SelectionDAG &DAG) const {
13324   MVT VT = Op.getSimpleValueType();
13325   MVT EltVT = VT.getVectorElementType();
13326
13327   if (EltVT == MVT::i1)
13328     return InsertBitToMaskVector(Op, DAG);
13329
13330   SDLoc dl(Op);
13331   SDValue N0 = Op.getOperand(0);
13332   SDValue N1 = Op.getOperand(1);
13333   SDValue N2 = Op.getOperand(2);
13334   if (!isa<ConstantSDNode>(N2))
13335     return SDValue();
13336   auto *N2C = cast<ConstantSDNode>(N2);
13337   unsigned IdxVal = N2C->getZExtValue();
13338
13339   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
13340   // into that, and then insert the subvector back into the result.
13341   if (VT.is256BitVector() || VT.is512BitVector()) {
13342     // Get the desired 128-bit vector half.
13343     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
13344
13345     // Insert the element into the desired half.
13346     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
13347     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
13348
13349     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
13350                     DAG.getConstant(IdxIn128, MVT::i32));
13351
13352     // Insert the changed part back to the 256-bit vector
13353     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
13354   }
13355   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
13356
13357   if (Subtarget->hasSSE41()) {
13358     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
13359       unsigned Opc;
13360       if (VT == MVT::v8i16) {
13361         Opc = X86ISD::PINSRW;
13362       } else {
13363         assert(VT == MVT::v16i8);
13364         Opc = X86ISD::PINSRB;
13365       }
13366
13367       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
13368       // argument.
13369       if (N1.getValueType() != MVT::i32)
13370         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
13371       if (N2.getValueType() != MVT::i32)
13372         N2 = DAG.getIntPtrConstant(IdxVal);
13373       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
13374     }
13375
13376     if (EltVT == MVT::f32) {
13377       // Bits [7:6] of the constant are the source select.  This will always be
13378       //  zero here.  The DAG Combiner may combine an extract_elt index into
13379       //  these
13380       //  bits.  For example (insert (extract, 3), 2) could be matched by
13381       //  putting
13382       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
13383       // Bits [5:4] of the constant are the destination select.  This is the
13384       //  value of the incoming immediate.
13385       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
13386       //   combine either bitwise AND or insert of float 0.0 to set these bits.
13387       N2 = DAG.getIntPtrConstant(IdxVal << 4);
13388       // Create this as a scalar to vector..
13389       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
13390       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
13391     }
13392
13393     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
13394       // PINSR* works with constant index.
13395       return Op;
13396     }
13397   }
13398
13399   if (EltVT == MVT::i8)
13400     return SDValue();
13401
13402   if (EltVT.getSizeInBits() == 16) {
13403     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
13404     // as its second argument.
13405     if (N1.getValueType() != MVT::i32)
13406       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
13407     if (N2.getValueType() != MVT::i32)
13408       N2 = DAG.getIntPtrConstant(IdxVal);
13409     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
13410   }
13411   return SDValue();
13412 }
13413
13414 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
13415   SDLoc dl(Op);
13416   MVT OpVT = Op.getSimpleValueType();
13417
13418   // If this is a 256-bit vector result, first insert into a 128-bit
13419   // vector and then insert into the 256-bit vector.
13420   if (!OpVT.is128BitVector()) {
13421     // Insert into a 128-bit vector.
13422     unsigned SizeFactor = OpVT.getSizeInBits()/128;
13423     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
13424                                  OpVT.getVectorNumElements() / SizeFactor);
13425
13426     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
13427
13428     // Insert the 128-bit vector.
13429     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
13430   }
13431
13432   if (OpVT == MVT::v1i64 &&
13433       Op.getOperand(0).getValueType() == MVT::i64)
13434     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
13435
13436   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
13437   assert(OpVT.is128BitVector() && "Expected an SSE type!");
13438   return DAG.getNode(ISD::BITCAST, dl, OpVT,
13439                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
13440 }
13441
13442 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
13443 // a simple subregister reference or explicit instructions to grab
13444 // upper bits of a vector.
13445 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
13446                                       SelectionDAG &DAG) {
13447   SDLoc dl(Op);
13448   SDValue In =  Op.getOperand(0);
13449   SDValue Idx = Op.getOperand(1);
13450   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13451   MVT ResVT   = Op.getSimpleValueType();
13452   MVT InVT    = In.getSimpleValueType();
13453
13454   if (Subtarget->hasFp256()) {
13455     if (ResVT.is128BitVector() &&
13456         (InVT.is256BitVector() || InVT.is512BitVector()) &&
13457         isa<ConstantSDNode>(Idx)) {
13458       return Extract128BitVector(In, IdxVal, DAG, dl);
13459     }
13460     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
13461         isa<ConstantSDNode>(Idx)) {
13462       return Extract256BitVector(In, IdxVal, DAG, dl);
13463     }
13464   }
13465   return SDValue();
13466 }
13467
13468 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
13469 // simple superregister reference or explicit instructions to insert
13470 // the upper bits of a vector.
13471 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
13472                                      SelectionDAG &DAG) {
13473   if (!Subtarget->hasAVX())
13474     return SDValue();
13475
13476   SDLoc dl(Op);
13477   SDValue Vec = Op.getOperand(0);
13478   SDValue SubVec = Op.getOperand(1);
13479   SDValue Idx = Op.getOperand(2);
13480
13481   if (!isa<ConstantSDNode>(Idx))
13482     return SDValue();
13483
13484   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13485   MVT OpVT = Op.getSimpleValueType();
13486   MVT SubVecVT = SubVec.getSimpleValueType();
13487
13488   // Fold two 16-byte subvector loads into one 32-byte load:
13489   // (insert_subvector (insert_subvector undef, (load addr), 0),
13490   //                   (load addr + 16), Elts/2)
13491   // --> load32 addr
13492   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
13493       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
13494       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
13495       !Subtarget->isUnalignedMem32Slow()) {
13496     SDValue SubVec2 = Vec.getOperand(1);
13497     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
13498       if (Idx2->getZExtValue() == 0) {
13499         SDValue Ops[] = { SubVec2, SubVec };
13500         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
13501         if (LD.getNode())
13502           return LD;
13503       }
13504     }
13505   }
13506
13507   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
13508       SubVecVT.is128BitVector())
13509     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
13510
13511   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
13512     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
13513
13514   return SDValue();
13515 }
13516
13517 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
13518 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
13519 // one of the above mentioned nodes. It has to be wrapped because otherwise
13520 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
13521 // be used to form addressing mode. These wrapped nodes will be selected
13522 // into MOV32ri.
13523 SDValue
13524 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
13525   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
13526
13527   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13528   // global base reg.
13529   unsigned char OpFlag = 0;
13530   unsigned WrapperKind = X86ISD::Wrapper;
13531   CodeModel::Model M = DAG.getTarget().getCodeModel();
13532
13533   if (Subtarget->isPICStyleRIPRel() &&
13534       (M == CodeModel::Small || M == CodeModel::Kernel))
13535     WrapperKind = X86ISD::WrapperRIP;
13536   else if (Subtarget->isPICStyleGOT())
13537     OpFlag = X86II::MO_GOTOFF;
13538   else if (Subtarget->isPICStyleStubPIC())
13539     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13540
13541   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
13542                                              CP->getAlignment(),
13543                                              CP->getOffset(), OpFlag);
13544   SDLoc DL(CP);
13545   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13546   // With PIC, the address is actually $g + Offset.
13547   if (OpFlag) {
13548     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13549                          DAG.getNode(X86ISD::GlobalBaseReg,
13550                                      SDLoc(), getPointerTy()),
13551                          Result);
13552   }
13553
13554   return Result;
13555 }
13556
13557 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
13558   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
13559
13560   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13561   // global base reg.
13562   unsigned char OpFlag = 0;
13563   unsigned WrapperKind = X86ISD::Wrapper;
13564   CodeModel::Model M = DAG.getTarget().getCodeModel();
13565
13566   if (Subtarget->isPICStyleRIPRel() &&
13567       (M == CodeModel::Small || M == CodeModel::Kernel))
13568     WrapperKind = X86ISD::WrapperRIP;
13569   else if (Subtarget->isPICStyleGOT())
13570     OpFlag = X86II::MO_GOTOFF;
13571   else if (Subtarget->isPICStyleStubPIC())
13572     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13573
13574   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
13575                                           OpFlag);
13576   SDLoc DL(JT);
13577   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13578
13579   // With PIC, the address is actually $g + Offset.
13580   if (OpFlag)
13581     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13582                          DAG.getNode(X86ISD::GlobalBaseReg,
13583                                      SDLoc(), getPointerTy()),
13584                          Result);
13585
13586   return Result;
13587 }
13588
13589 SDValue
13590 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
13591   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13592
13593   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13594   // global base reg.
13595   unsigned char OpFlag = 0;
13596   unsigned WrapperKind = X86ISD::Wrapper;
13597   CodeModel::Model M = DAG.getTarget().getCodeModel();
13598
13599   if (Subtarget->isPICStyleRIPRel() &&
13600       (M == CodeModel::Small || M == CodeModel::Kernel)) {
13601     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
13602       OpFlag = X86II::MO_GOTPCREL;
13603     WrapperKind = X86ISD::WrapperRIP;
13604   } else if (Subtarget->isPICStyleGOT()) {
13605     OpFlag = X86II::MO_GOT;
13606   } else if (Subtarget->isPICStyleStubPIC()) {
13607     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
13608   } else if (Subtarget->isPICStyleStubNoDynamic()) {
13609     OpFlag = X86II::MO_DARWIN_NONLAZY;
13610   }
13611
13612   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
13613
13614   SDLoc DL(Op);
13615   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13616
13617   // With PIC, the address is actually $g + Offset.
13618   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
13619       !Subtarget->is64Bit()) {
13620     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13621                          DAG.getNode(X86ISD::GlobalBaseReg,
13622                                      SDLoc(), getPointerTy()),
13623                          Result);
13624   }
13625
13626   // For symbols that require a load from a stub to get the address, emit the
13627   // load.
13628   if (isGlobalStubReference(OpFlag))
13629     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
13630                          MachinePointerInfo::getGOT(), false, false, false, 0);
13631
13632   return Result;
13633 }
13634
13635 SDValue
13636 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
13637   // Create the TargetBlockAddressAddress node.
13638   unsigned char OpFlags =
13639     Subtarget->ClassifyBlockAddressReference();
13640   CodeModel::Model M = DAG.getTarget().getCodeModel();
13641   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
13642   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
13643   SDLoc dl(Op);
13644   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
13645                                              OpFlags);
13646
13647   if (Subtarget->isPICStyleRIPRel() &&
13648       (M == CodeModel::Small || M == CodeModel::Kernel))
13649     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13650   else
13651     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13652
13653   // With PIC, the address is actually $g + Offset.
13654   if (isGlobalRelativeToPICBase(OpFlags)) {
13655     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13656                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13657                          Result);
13658   }
13659
13660   return Result;
13661 }
13662
13663 SDValue
13664 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
13665                                       int64_t Offset, SelectionDAG &DAG) const {
13666   // Create the TargetGlobalAddress node, folding in the constant
13667   // offset if it is legal.
13668   unsigned char OpFlags =
13669       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
13670   CodeModel::Model M = DAG.getTarget().getCodeModel();
13671   SDValue Result;
13672   if (OpFlags == X86II::MO_NO_FLAG &&
13673       X86::isOffsetSuitableForCodeModel(Offset, M)) {
13674     // A direct static reference to a global.
13675     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
13676     Offset = 0;
13677   } else {
13678     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
13679   }
13680
13681   if (Subtarget->isPICStyleRIPRel() &&
13682       (M == CodeModel::Small || M == CodeModel::Kernel))
13683     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13684   else
13685     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13686
13687   // With PIC, the address is actually $g + Offset.
13688   if (isGlobalRelativeToPICBase(OpFlags)) {
13689     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13690                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13691                          Result);
13692   }
13693
13694   // For globals that require a load from a stub to get the address, emit the
13695   // load.
13696   if (isGlobalStubReference(OpFlags))
13697     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
13698                          MachinePointerInfo::getGOT(), false, false, false, 0);
13699
13700   // If there was a non-zero offset that we didn't fold, create an explicit
13701   // addition for it.
13702   if (Offset != 0)
13703     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
13704                          DAG.getConstant(Offset, getPointerTy()));
13705
13706   return Result;
13707 }
13708
13709 SDValue
13710 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
13711   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
13712   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
13713   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
13714 }
13715
13716 static SDValue
13717 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
13718            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
13719            unsigned char OperandFlags, bool LocalDynamic = false) {
13720   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13721   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13722   SDLoc dl(GA);
13723   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13724                                            GA->getValueType(0),
13725                                            GA->getOffset(),
13726                                            OperandFlags);
13727
13728   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
13729                                            : X86ISD::TLSADDR;
13730
13731   if (InFlag) {
13732     SDValue Ops[] = { Chain,  TGA, *InFlag };
13733     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13734   } else {
13735     SDValue Ops[]  = { Chain, TGA };
13736     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13737   }
13738
13739   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
13740   MFI->setAdjustsStack(true);
13741   MFI->setHasCalls(true);
13742
13743   SDValue Flag = Chain.getValue(1);
13744   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
13745 }
13746
13747 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
13748 static SDValue
13749 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13750                                 const EVT PtrVT) {
13751   SDValue InFlag;
13752   SDLoc dl(GA);  // ? function entry point might be better
13753   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13754                                    DAG.getNode(X86ISD::GlobalBaseReg,
13755                                                SDLoc(), PtrVT), InFlag);
13756   InFlag = Chain.getValue(1);
13757
13758   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
13759 }
13760
13761 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
13762 static SDValue
13763 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13764                                 const EVT PtrVT) {
13765   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
13766                     X86::RAX, X86II::MO_TLSGD);
13767 }
13768
13769 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
13770                                            SelectionDAG &DAG,
13771                                            const EVT PtrVT,
13772                                            bool is64Bit) {
13773   SDLoc dl(GA);
13774
13775   // Get the start address of the TLS block for this module.
13776   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
13777       .getInfo<X86MachineFunctionInfo>();
13778   MFI->incNumLocalDynamicTLSAccesses();
13779
13780   SDValue Base;
13781   if (is64Bit) {
13782     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
13783                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
13784   } else {
13785     SDValue InFlag;
13786     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13787         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
13788     InFlag = Chain.getValue(1);
13789     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
13790                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
13791   }
13792
13793   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
13794   // of Base.
13795
13796   // Build x@dtpoff.
13797   unsigned char OperandFlags = X86II::MO_DTPOFF;
13798   unsigned WrapperKind = X86ISD::Wrapper;
13799   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13800                                            GA->getValueType(0),
13801                                            GA->getOffset(), OperandFlags);
13802   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13803
13804   // Add x@dtpoff with the base.
13805   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
13806 }
13807
13808 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
13809 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13810                                    const EVT PtrVT, TLSModel::Model model,
13811                                    bool is64Bit, bool isPIC) {
13812   SDLoc dl(GA);
13813
13814   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
13815   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
13816                                                          is64Bit ? 257 : 256));
13817
13818   SDValue ThreadPointer =
13819       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
13820                   MachinePointerInfo(Ptr), false, false, false, 0);
13821
13822   unsigned char OperandFlags = 0;
13823   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
13824   // initialexec.
13825   unsigned WrapperKind = X86ISD::Wrapper;
13826   if (model == TLSModel::LocalExec) {
13827     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
13828   } else if (model == TLSModel::InitialExec) {
13829     if (is64Bit) {
13830       OperandFlags = X86II::MO_GOTTPOFF;
13831       WrapperKind = X86ISD::WrapperRIP;
13832     } else {
13833       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
13834     }
13835   } else {
13836     llvm_unreachable("Unexpected model");
13837   }
13838
13839   // emit "addl x@ntpoff,%eax" (local exec)
13840   // or "addl x@indntpoff,%eax" (initial exec)
13841   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
13842   SDValue TGA =
13843       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
13844                                  GA->getOffset(), OperandFlags);
13845   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13846
13847   if (model == TLSModel::InitialExec) {
13848     if (isPIC && !is64Bit) {
13849       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
13850                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
13851                            Offset);
13852     }
13853
13854     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
13855                          MachinePointerInfo::getGOT(), false, false, false, 0);
13856   }
13857
13858   // The address of the thread local variable is the add of the thread
13859   // pointer with the offset of the variable.
13860   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
13861 }
13862
13863 SDValue
13864 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
13865
13866   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
13867   const GlobalValue *GV = GA->getGlobal();
13868
13869   if (Subtarget->isTargetELF()) {
13870     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
13871
13872     switch (model) {
13873       case TLSModel::GeneralDynamic:
13874         if (Subtarget->is64Bit())
13875           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
13876         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
13877       case TLSModel::LocalDynamic:
13878         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
13879                                            Subtarget->is64Bit());
13880       case TLSModel::InitialExec:
13881       case TLSModel::LocalExec:
13882         return LowerToTLSExecModel(
13883             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
13884             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
13885     }
13886     llvm_unreachable("Unknown TLS model.");
13887   }
13888
13889   if (Subtarget->isTargetDarwin()) {
13890     // Darwin only has one model of TLS.  Lower to that.
13891     unsigned char OpFlag = 0;
13892     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
13893                            X86ISD::WrapperRIP : X86ISD::Wrapper;
13894
13895     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13896     // global base reg.
13897     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
13898                  !Subtarget->is64Bit();
13899     if (PIC32)
13900       OpFlag = X86II::MO_TLVP_PIC_BASE;
13901     else
13902       OpFlag = X86II::MO_TLVP;
13903     SDLoc DL(Op);
13904     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
13905                                                 GA->getValueType(0),
13906                                                 GA->getOffset(), OpFlag);
13907     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13908
13909     // With PIC32, the address is actually $g + Offset.
13910     if (PIC32)
13911       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13912                            DAG.getNode(X86ISD::GlobalBaseReg,
13913                                        SDLoc(), getPointerTy()),
13914                            Offset);
13915
13916     // Lowering the machine isd will make sure everything is in the right
13917     // location.
13918     SDValue Chain = DAG.getEntryNode();
13919     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13920     SDValue Args[] = { Chain, Offset };
13921     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
13922
13923     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
13924     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13925     MFI->setAdjustsStack(true);
13926
13927     // And our return value (tls address) is in the standard call return value
13928     // location.
13929     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13930     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
13931                               Chain.getValue(1));
13932   }
13933
13934   if (Subtarget->isTargetKnownWindowsMSVC() ||
13935       Subtarget->isTargetWindowsGNU()) {
13936     // Just use the implicit TLS architecture
13937     // Need to generate someting similar to:
13938     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
13939     //                                  ; from TEB
13940     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
13941     //   mov     rcx, qword [rdx+rcx*8]
13942     //   mov     eax, .tls$:tlsvar
13943     //   [rax+rcx] contains the address
13944     // Windows 64bit: gs:0x58
13945     // Windows 32bit: fs:__tls_array
13946
13947     SDLoc dl(GA);
13948     SDValue Chain = DAG.getEntryNode();
13949
13950     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
13951     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
13952     // use its literal value of 0x2C.
13953     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
13954                                         ? Type::getInt8PtrTy(*DAG.getContext(),
13955                                                              256)
13956                                         : Type::getInt32PtrTy(*DAG.getContext(),
13957                                                               257));
13958
13959     SDValue TlsArray =
13960         Subtarget->is64Bit()
13961             ? DAG.getIntPtrConstant(0x58)
13962             : (Subtarget->isTargetWindowsGNU()
13963                    ? DAG.getIntPtrConstant(0x2C)
13964                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
13965
13966     SDValue ThreadPointer =
13967         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
13968                     MachinePointerInfo(Ptr), false, false, false, 0);
13969
13970     // Load the _tls_index variable
13971     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
13972     if (Subtarget->is64Bit())
13973       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
13974                            IDX, MachinePointerInfo(), MVT::i32,
13975                            false, false, false, 0);
13976     else
13977       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
13978                         false, false, false, 0);
13979
13980     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
13981                                     getPointerTy());
13982     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
13983
13984     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
13985     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
13986                       false, false, false, 0);
13987
13988     // Get the offset of start of .tls section
13989     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13990                                              GA->getValueType(0),
13991                                              GA->getOffset(), X86II::MO_SECREL);
13992     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
13993
13994     // The address of the thread local variable is the add of the thread
13995     // pointer with the offset of the variable.
13996     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
13997   }
13998
13999   llvm_unreachable("TLS not implemented for this target.");
14000 }
14001
14002 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
14003 /// and take a 2 x i32 value to shift plus a shift amount.
14004 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
14005   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
14006   MVT VT = Op.getSimpleValueType();
14007   unsigned VTBits = VT.getSizeInBits();
14008   SDLoc dl(Op);
14009   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
14010   SDValue ShOpLo = Op.getOperand(0);
14011   SDValue ShOpHi = Op.getOperand(1);
14012   SDValue ShAmt  = Op.getOperand(2);
14013   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
14014   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
14015   // during isel.
14016   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
14017                                   DAG.getConstant(VTBits - 1, MVT::i8));
14018   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
14019                                      DAG.getConstant(VTBits - 1, MVT::i8))
14020                        : DAG.getConstant(0, VT);
14021
14022   SDValue Tmp2, Tmp3;
14023   if (Op.getOpcode() == ISD::SHL_PARTS) {
14024     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
14025     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
14026   } else {
14027     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
14028     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
14029   }
14030
14031   // If the shift amount is larger or equal than the width of a part we can't
14032   // rely on the results of shld/shrd. Insert a test and select the appropriate
14033   // values for large shift amounts.
14034   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
14035                                 DAG.getConstant(VTBits, MVT::i8));
14036   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14037                              AndNode, DAG.getConstant(0, MVT::i8));
14038
14039   SDValue Hi, Lo;
14040   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14041   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
14042   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
14043
14044   if (Op.getOpcode() == ISD::SHL_PARTS) {
14045     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
14046     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
14047   } else {
14048     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
14049     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
14050   }
14051
14052   SDValue Ops[2] = { Lo, Hi };
14053   return DAG.getMergeValues(Ops, dl);
14054 }
14055
14056 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
14057                                            SelectionDAG &DAG) const {
14058   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14059   SDLoc dl(Op);
14060
14061   if (SrcVT.isVector()) {
14062     if (SrcVT.getVectorElementType() == MVT::i1) {
14063       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
14064       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
14065                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
14066                                      Op.getOperand(0)));
14067     }
14068     return SDValue();
14069   }
14070
14071   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
14072          "Unknown SINT_TO_FP to lower!");
14073
14074   // These are really Legal; return the operand so the caller accepts it as
14075   // Legal.
14076   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
14077     return Op;
14078   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
14079       Subtarget->is64Bit()) {
14080     return Op;
14081   }
14082
14083   unsigned Size = SrcVT.getSizeInBits()/8;
14084   MachineFunction &MF = DAG.getMachineFunction();
14085   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
14086   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14087   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
14088                                StackSlot,
14089                                MachinePointerInfo::getFixedStack(SSFI),
14090                                false, false, 0);
14091   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
14092 }
14093
14094 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
14095                                      SDValue StackSlot,
14096                                      SelectionDAG &DAG) const {
14097   // Build the FILD
14098   SDLoc DL(Op);
14099   SDVTList Tys;
14100   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
14101   if (useSSE)
14102     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
14103   else
14104     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
14105
14106   unsigned ByteSize = SrcVT.getSizeInBits()/8;
14107
14108   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
14109   MachineMemOperand *MMO;
14110   if (FI) {
14111     int SSFI = FI->getIndex();
14112     MMO =
14113       DAG.getMachineFunction()
14114       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14115                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
14116   } else {
14117     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
14118     StackSlot = StackSlot.getOperand(1);
14119   }
14120   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
14121   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
14122                                            X86ISD::FILD, DL,
14123                                            Tys, Ops, SrcVT, MMO);
14124
14125   if (useSSE) {
14126     Chain = Result.getValue(1);
14127     SDValue InFlag = Result.getValue(2);
14128
14129     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
14130     // shouldn't be necessary except that RFP cannot be live across
14131     // multiple blocks. When stackifier is fixed, they can be uncoupled.
14132     MachineFunction &MF = DAG.getMachineFunction();
14133     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
14134     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
14135     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14136     Tys = DAG.getVTList(MVT::Other);
14137     SDValue Ops[] = {
14138       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
14139     };
14140     MachineMemOperand *MMO =
14141       DAG.getMachineFunction()
14142       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14143                             MachineMemOperand::MOStore, SSFISize, SSFISize);
14144
14145     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
14146                                     Ops, Op.getValueType(), MMO);
14147     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
14148                          MachinePointerInfo::getFixedStack(SSFI),
14149                          false, false, false, 0);
14150   }
14151
14152   return Result;
14153 }
14154
14155 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
14156 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
14157                                                SelectionDAG &DAG) const {
14158   // This algorithm is not obvious. Here it is what we're trying to output:
14159   /*
14160      movq       %rax,  %xmm0
14161      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
14162      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
14163      #ifdef __SSE3__
14164        haddpd   %xmm0, %xmm0
14165      #else
14166        pshufd   $0x4e, %xmm0, %xmm1
14167        addpd    %xmm1, %xmm0
14168      #endif
14169   */
14170
14171   SDLoc dl(Op);
14172   LLVMContext *Context = DAG.getContext();
14173
14174   // Build some magic constants.
14175   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
14176   Constant *C0 = ConstantDataVector::get(*Context, CV0);
14177   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
14178
14179   SmallVector<Constant*,2> CV1;
14180   CV1.push_back(
14181     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
14182                                       APInt(64, 0x4330000000000000ULL))));
14183   CV1.push_back(
14184     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
14185                                       APInt(64, 0x4530000000000000ULL))));
14186   Constant *C1 = ConstantVector::get(CV1);
14187   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
14188
14189   // Load the 64-bit value into an XMM register.
14190   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
14191                             Op.getOperand(0));
14192   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
14193                               MachinePointerInfo::getConstantPool(),
14194                               false, false, false, 16);
14195   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
14196                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
14197                               CLod0);
14198
14199   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
14200                               MachinePointerInfo::getConstantPool(),
14201                               false, false, false, 16);
14202   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
14203   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
14204   SDValue Result;
14205
14206   if (Subtarget->hasSSE3()) {
14207     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
14208     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
14209   } else {
14210     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
14211     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
14212                                            S2F, 0x4E, DAG);
14213     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
14214                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
14215                          Sub);
14216   }
14217
14218   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
14219                      DAG.getIntPtrConstant(0));
14220 }
14221
14222 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
14223 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
14224                                                SelectionDAG &DAG) const {
14225   SDLoc dl(Op);
14226   // FP constant to bias correct the final result.
14227   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14228                                    MVT::f64);
14229
14230   // Load the 32-bit value into an XMM register.
14231   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
14232                              Op.getOperand(0));
14233
14234   // Zero out the upper parts of the register.
14235   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
14236
14237   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14238                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
14239                      DAG.getIntPtrConstant(0));
14240
14241   // Or the load with the bias.
14242   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
14243                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
14244                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14245                                                    MVT::v2f64, Load)),
14246                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
14247                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14248                                                    MVT::v2f64, Bias)));
14249   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14250                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
14251                    DAG.getIntPtrConstant(0));
14252
14253   // Subtract the bias.
14254   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
14255
14256   // Handle final rounding.
14257   EVT DestVT = Op.getValueType();
14258
14259   if (DestVT.bitsLT(MVT::f64))
14260     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
14261                        DAG.getIntPtrConstant(0));
14262   if (DestVT.bitsGT(MVT::f64))
14263     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
14264
14265   // Handle final rounding.
14266   return Sub;
14267 }
14268
14269 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
14270                                      const X86Subtarget &Subtarget) {
14271   // The algorithm is the following:
14272   // #ifdef __SSE4_1__
14273   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
14274   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
14275   //                                 (uint4) 0x53000000, 0xaa);
14276   // #else
14277   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
14278   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
14279   // #endif
14280   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
14281   //     return (float4) lo + fhi;
14282
14283   SDLoc DL(Op);
14284   SDValue V = Op->getOperand(0);
14285   EVT VecIntVT = V.getValueType();
14286   bool Is128 = VecIntVT == MVT::v4i32;
14287   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
14288   // If we convert to something else than the supported type, e.g., to v4f64,
14289   // abort early.
14290   if (VecFloatVT != Op->getValueType(0))
14291     return SDValue();
14292
14293   unsigned NumElts = VecIntVT.getVectorNumElements();
14294   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
14295          "Unsupported custom type");
14296   assert(NumElts <= 8 && "The size of the constant array must be fixed");
14297
14298   // In the #idef/#else code, we have in common:
14299   // - The vector of constants:
14300   // -- 0x4b000000
14301   // -- 0x53000000
14302   // - A shift:
14303   // -- v >> 16
14304
14305   // Create the splat vector for 0x4b000000.
14306   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
14307   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
14308                            CstLow, CstLow, CstLow, CstLow};
14309   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
14310                                   makeArrayRef(&CstLowArray[0], NumElts));
14311   // Create the splat vector for 0x53000000.
14312   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
14313   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
14314                             CstHigh, CstHigh, CstHigh, CstHigh};
14315   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
14316                                    makeArrayRef(&CstHighArray[0], NumElts));
14317
14318   // Create the right shift.
14319   SDValue CstShift = DAG.getConstant(16, MVT::i32);
14320   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
14321                              CstShift, CstShift, CstShift, CstShift};
14322   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
14323                                     makeArrayRef(&CstShiftArray[0], NumElts));
14324   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
14325
14326   SDValue Low, High;
14327   if (Subtarget.hasSSE41()) {
14328     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
14329     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
14330     SDValue VecCstLowBitcast =
14331         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
14332     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
14333     // Low will be bitcasted right away, so do not bother bitcasting back to its
14334     // original type.
14335     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
14336                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
14337     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
14338     //                                 (uint4) 0x53000000, 0xaa);
14339     SDValue VecCstHighBitcast =
14340         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
14341     SDValue VecShiftBitcast =
14342         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
14343     // High will be bitcasted right away, so do not bother bitcasting back to
14344     // its original type.
14345     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
14346                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
14347   } else {
14348     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
14349     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
14350                                      CstMask, CstMask, CstMask);
14351     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
14352     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
14353     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
14354
14355     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
14356     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
14357   }
14358
14359   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
14360   SDValue CstFAdd = DAG.getConstantFP(
14361       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
14362   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
14363                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
14364   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
14365                                    makeArrayRef(&CstFAddArray[0], NumElts));
14366
14367   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
14368   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
14369   SDValue FHigh =
14370       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
14371   //     return (float4) lo + fhi;
14372   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
14373   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
14374 }
14375
14376 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
14377                                                SelectionDAG &DAG) const {
14378   SDValue N0 = Op.getOperand(0);
14379   MVT SVT = N0.getSimpleValueType();
14380   SDLoc dl(Op);
14381
14382   switch (SVT.SimpleTy) {
14383   default:
14384     llvm_unreachable("Custom UINT_TO_FP is not supported!");
14385   case MVT::v4i8:
14386   case MVT::v4i16:
14387   case MVT::v8i8:
14388   case MVT::v8i16: {
14389     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
14390     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
14391                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
14392   }
14393   case MVT::v4i32:
14394   case MVT::v8i32:
14395     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
14396   }
14397   llvm_unreachable(nullptr);
14398 }
14399
14400 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
14401                                            SelectionDAG &DAG) const {
14402   SDValue N0 = Op.getOperand(0);
14403   SDLoc dl(Op);
14404
14405   if (Op.getValueType().isVector())
14406     return lowerUINT_TO_FP_vec(Op, DAG);
14407
14408   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
14409   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
14410   // the optimization here.
14411   if (DAG.SignBitIsZero(N0))
14412     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
14413
14414   MVT SrcVT = N0.getSimpleValueType();
14415   MVT DstVT = Op.getSimpleValueType();
14416   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
14417     return LowerUINT_TO_FP_i64(Op, DAG);
14418   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
14419     return LowerUINT_TO_FP_i32(Op, DAG);
14420   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
14421     return SDValue();
14422
14423   // Make a 64-bit buffer, and use it to build an FILD.
14424   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
14425   if (SrcVT == MVT::i32) {
14426     SDValue WordOff = DAG.getConstant(4, getPointerTy());
14427     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
14428                                      getPointerTy(), StackSlot, WordOff);
14429     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
14430                                   StackSlot, MachinePointerInfo(),
14431                                   false, false, 0);
14432     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
14433                                   OffsetSlot, MachinePointerInfo(),
14434                                   false, false, 0);
14435     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
14436     return Fild;
14437   }
14438
14439   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
14440   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
14441                                StackSlot, MachinePointerInfo(),
14442                                false, false, 0);
14443   // For i64 source, we need to add the appropriate power of 2 if the input
14444   // was negative.  This is the same as the optimization in
14445   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
14446   // we must be careful to do the computation in x87 extended precision, not
14447   // in SSE. (The generic code can't know it's OK to do this, or how to.)
14448   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
14449   MachineMemOperand *MMO =
14450     DAG.getMachineFunction()
14451     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14452                           MachineMemOperand::MOLoad, 8, 8);
14453
14454   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
14455   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
14456   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
14457                                          MVT::i64, MMO);
14458
14459   APInt FF(32, 0x5F800000ULL);
14460
14461   // Check whether the sign bit is set.
14462   SDValue SignSet = DAG.getSetCC(dl,
14463                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
14464                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
14465                                  ISD::SETLT);
14466
14467   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
14468   SDValue FudgePtr = DAG.getConstantPool(
14469                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
14470                                          getPointerTy());
14471
14472   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
14473   SDValue Zero = DAG.getIntPtrConstant(0);
14474   SDValue Four = DAG.getIntPtrConstant(4);
14475   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
14476                                Zero, Four);
14477   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
14478
14479   // Load the value out, extending it from f32 to f80.
14480   // FIXME: Avoid the extend by constructing the right constant pool?
14481   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
14482                                  FudgePtr, MachinePointerInfo::getConstantPool(),
14483                                  MVT::f32, false, false, false, 4);
14484   // Extend everything to 80 bits to force it to be done on x87.
14485   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
14486   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
14487 }
14488
14489 std::pair<SDValue,SDValue>
14490 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
14491                                     bool IsSigned, bool IsReplace) const {
14492   SDLoc DL(Op);
14493
14494   EVT DstTy = Op.getValueType();
14495
14496   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
14497     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
14498     DstTy = MVT::i64;
14499   }
14500
14501   assert(DstTy.getSimpleVT() <= MVT::i64 &&
14502          DstTy.getSimpleVT() >= MVT::i16 &&
14503          "Unknown FP_TO_INT to lower!");
14504
14505   // These are really Legal.
14506   if (DstTy == MVT::i32 &&
14507       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14508     return std::make_pair(SDValue(), SDValue());
14509   if (Subtarget->is64Bit() &&
14510       DstTy == MVT::i64 &&
14511       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14512     return std::make_pair(SDValue(), SDValue());
14513
14514   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
14515   // stack slot, or into the FTOL runtime function.
14516   MachineFunction &MF = DAG.getMachineFunction();
14517   unsigned MemSize = DstTy.getSizeInBits()/8;
14518   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14519   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14520
14521   unsigned Opc;
14522   if (!IsSigned && isIntegerTypeFTOL(DstTy))
14523     Opc = X86ISD::WIN_FTOL;
14524   else
14525     switch (DstTy.getSimpleVT().SimpleTy) {
14526     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
14527     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
14528     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
14529     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
14530     }
14531
14532   SDValue Chain = DAG.getEntryNode();
14533   SDValue Value = Op.getOperand(0);
14534   EVT TheVT = Op.getOperand(0).getValueType();
14535   // FIXME This causes a redundant load/store if the SSE-class value is already
14536   // in memory, such as if it is on the callstack.
14537   if (isScalarFPTypeInSSEReg(TheVT)) {
14538     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
14539     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
14540                          MachinePointerInfo::getFixedStack(SSFI),
14541                          false, false, 0);
14542     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
14543     SDValue Ops[] = {
14544       Chain, StackSlot, DAG.getValueType(TheVT)
14545     };
14546
14547     MachineMemOperand *MMO =
14548       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14549                               MachineMemOperand::MOLoad, MemSize, MemSize);
14550     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
14551     Chain = Value.getValue(1);
14552     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14553     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14554   }
14555
14556   MachineMemOperand *MMO =
14557     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14558                             MachineMemOperand::MOStore, MemSize, MemSize);
14559
14560   if (Opc != X86ISD::WIN_FTOL) {
14561     // Build the FP_TO_INT*_IN_MEM
14562     SDValue Ops[] = { Chain, Value, StackSlot };
14563     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
14564                                            Ops, DstTy, MMO);
14565     return std::make_pair(FIST, StackSlot);
14566   } else {
14567     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
14568       DAG.getVTList(MVT::Other, MVT::Glue),
14569       Chain, Value);
14570     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
14571       MVT::i32, ftol.getValue(1));
14572     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
14573       MVT::i32, eax.getValue(2));
14574     SDValue Ops[] = { eax, edx };
14575     SDValue pair = IsReplace
14576       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
14577       : DAG.getMergeValues(Ops, DL);
14578     return std::make_pair(pair, SDValue());
14579   }
14580 }
14581
14582 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
14583                               const X86Subtarget *Subtarget) {
14584   MVT VT = Op->getSimpleValueType(0);
14585   SDValue In = Op->getOperand(0);
14586   MVT InVT = In.getSimpleValueType();
14587   SDLoc dl(Op);
14588
14589   // Optimize vectors in AVX mode:
14590   //
14591   //   v8i16 -> v8i32
14592   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
14593   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
14594   //   Concat upper and lower parts.
14595   //
14596   //   v4i32 -> v4i64
14597   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
14598   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
14599   //   Concat upper and lower parts.
14600   //
14601
14602   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
14603       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
14604       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
14605     return SDValue();
14606
14607   if (Subtarget->hasInt256())
14608     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
14609
14610   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
14611   SDValue Undef = DAG.getUNDEF(InVT);
14612   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
14613   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14614   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14615
14616   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
14617                              VT.getVectorNumElements()/2);
14618
14619   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14620   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14621
14622   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14623 }
14624
14625 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
14626                                         SelectionDAG &DAG) {
14627   MVT VT = Op->getSimpleValueType(0);
14628   SDValue In = Op->getOperand(0);
14629   MVT InVT = In.getSimpleValueType();
14630   SDLoc DL(Op);
14631   unsigned int NumElts = VT.getVectorNumElements();
14632   if (NumElts != 8 && NumElts != 16)
14633     return SDValue();
14634
14635   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
14636     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
14637
14638   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
14639   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14640   // Now we have only mask extension
14641   assert(InVT.getVectorElementType() == MVT::i1);
14642   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
14643   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14644   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
14645   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14646   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14647                            MachinePointerInfo::getConstantPool(),
14648                            false, false, false, Alignment);
14649
14650   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
14651   if (VT.is512BitVector())
14652     return Brcst;
14653   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
14654 }
14655
14656 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14657                                SelectionDAG &DAG) {
14658   if (Subtarget->hasFp256()) {
14659     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14660     if (Res.getNode())
14661       return Res;
14662   }
14663
14664   return SDValue();
14665 }
14666
14667 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14668                                 SelectionDAG &DAG) {
14669   SDLoc DL(Op);
14670   MVT VT = Op.getSimpleValueType();
14671   SDValue In = Op.getOperand(0);
14672   MVT SVT = In.getSimpleValueType();
14673
14674   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
14675     return LowerZERO_EXTEND_AVX512(Op, DAG);
14676
14677   if (Subtarget->hasFp256()) {
14678     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14679     if (Res.getNode())
14680       return Res;
14681   }
14682
14683   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
14684          VT.getVectorNumElements() != SVT.getVectorNumElements());
14685   return SDValue();
14686 }
14687
14688 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
14689   SDLoc DL(Op);
14690   MVT VT = Op.getSimpleValueType();
14691   SDValue In = Op.getOperand(0);
14692   MVT InVT = In.getSimpleValueType();
14693
14694   if (VT == MVT::i1) {
14695     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
14696            "Invalid scalar TRUNCATE operation");
14697     if (InVT.getSizeInBits() >= 32)
14698       return SDValue();
14699     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
14700     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
14701   }
14702   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
14703          "Invalid TRUNCATE operation");
14704
14705   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
14706     if (VT.getVectorElementType().getSizeInBits() >=8)
14707       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
14708
14709     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14710     unsigned NumElts = InVT.getVectorNumElements();
14711     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
14712     if (InVT.getSizeInBits() < 512) {
14713       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
14714       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
14715       InVT = ExtVT;
14716     }
14717
14718     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
14719     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14720     SDValue CP = DAG.getConstantPool(C, getPointerTy());
14721     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14722     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14723                            MachinePointerInfo::getConstantPool(),
14724                            false, false, false, Alignment);
14725     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
14726     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
14727     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
14728   }
14729
14730   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
14731     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
14732     if (Subtarget->hasInt256()) {
14733       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14734       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
14735       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
14736                                 ShufMask);
14737       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
14738                          DAG.getIntPtrConstant(0));
14739     }
14740
14741     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14742                                DAG.getIntPtrConstant(0));
14743     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14744                                DAG.getIntPtrConstant(2));
14745     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14746     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14747     static const int ShufMask[] = {0, 2, 4, 6};
14748     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
14749   }
14750
14751   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
14752     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
14753     if (Subtarget->hasInt256()) {
14754       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
14755
14756       SmallVector<SDValue,32> pshufbMask;
14757       for (unsigned i = 0; i < 2; ++i) {
14758         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14759         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14760         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14761         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14762         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14763         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14764         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14765         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14766         for (unsigned j = 0; j < 8; ++j)
14767           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14768       }
14769       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
14770       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
14771       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
14772
14773       static const int ShufMask[] = {0,  2,  -1,  -1};
14774       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
14775                                 &ShufMask[0]);
14776       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14777                        DAG.getIntPtrConstant(0));
14778       return DAG.getNode(ISD::BITCAST, DL, VT, In);
14779     }
14780
14781     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14782                                DAG.getIntPtrConstant(0));
14783
14784     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14785                                DAG.getIntPtrConstant(4));
14786
14787     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
14788     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
14789
14790     // The PSHUFB mask:
14791     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14792                                    -1, -1, -1, -1, -1, -1, -1, -1};
14793
14794     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14795     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
14796     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
14797
14798     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14799     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14800
14801     // The MOVLHPS Mask:
14802     static const int ShufMask2[] = {0, 1, 4, 5};
14803     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
14804     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
14805   }
14806
14807   // Handle truncation of V256 to V128 using shuffles.
14808   if (!VT.is128BitVector() || !InVT.is256BitVector())
14809     return SDValue();
14810
14811   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
14812
14813   unsigned NumElems = VT.getVectorNumElements();
14814   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
14815
14816   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
14817   // Prepare truncation shuffle mask
14818   for (unsigned i = 0; i != NumElems; ++i)
14819     MaskVec[i] = i * 2;
14820   SDValue V = DAG.getVectorShuffle(NVT, DL,
14821                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
14822                                    DAG.getUNDEF(NVT), &MaskVec[0]);
14823   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
14824                      DAG.getIntPtrConstant(0));
14825 }
14826
14827 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
14828                                            SelectionDAG &DAG) const {
14829   assert(!Op.getSimpleValueType().isVector());
14830
14831   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14832     /*IsSigned=*/ true, /*IsReplace=*/ false);
14833   SDValue FIST = Vals.first, StackSlot = Vals.second;
14834   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
14835   if (!FIST.getNode()) return Op;
14836
14837   if (StackSlot.getNode())
14838     // Load the result.
14839     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14840                        FIST, StackSlot, MachinePointerInfo(),
14841                        false, false, false, 0);
14842
14843   // The node is the result.
14844   return FIST;
14845 }
14846
14847 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
14848                                            SelectionDAG &DAG) const {
14849   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14850     /*IsSigned=*/ false, /*IsReplace=*/ false);
14851   SDValue FIST = Vals.first, StackSlot = Vals.second;
14852   assert(FIST.getNode() && "Unexpected failure");
14853
14854   if (StackSlot.getNode())
14855     // Load the result.
14856     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14857                        FIST, StackSlot, MachinePointerInfo(),
14858                        false, false, false, 0);
14859
14860   // The node is the result.
14861   return FIST;
14862 }
14863
14864 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
14865   SDLoc DL(Op);
14866   MVT VT = Op.getSimpleValueType();
14867   SDValue In = Op.getOperand(0);
14868   MVT SVT = In.getSimpleValueType();
14869
14870   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
14871
14872   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
14873                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
14874                                  In, DAG.getUNDEF(SVT)));
14875 }
14876
14877 /// The only differences between FABS and FNEG are the mask and the logic op.
14878 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
14879 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
14880   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
14881          "Wrong opcode for lowering FABS or FNEG.");
14882
14883   bool IsFABS = (Op.getOpcode() == ISD::FABS);
14884
14885   // If this is a FABS and it has an FNEG user, bail out to fold the combination
14886   // into an FNABS. We'll lower the FABS after that if it is still in use.
14887   if (IsFABS)
14888     for (SDNode *User : Op->uses())
14889       if (User->getOpcode() == ISD::FNEG)
14890         return Op;
14891
14892   SDValue Op0 = Op.getOperand(0);
14893   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
14894
14895   SDLoc dl(Op);
14896   MVT VT = Op.getSimpleValueType();
14897   // Assume scalar op for initialization; update for vector if needed.
14898   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
14899   // generate a 16-byte vector constant and logic op even for the scalar case.
14900   // Using a 16-byte mask allows folding the load of the mask with
14901   // the logic op, so it can save (~4 bytes) on code size.
14902   MVT EltVT = VT;
14903   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
14904   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
14905   // decide if we should generate a 16-byte constant mask when we only need 4 or
14906   // 8 bytes for the scalar case.
14907   if (VT.isVector()) {
14908     EltVT = VT.getVectorElementType();
14909     NumElts = VT.getVectorNumElements();
14910   }
14911
14912   unsigned EltBits = EltVT.getSizeInBits();
14913   LLVMContext *Context = DAG.getContext();
14914   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
14915   APInt MaskElt =
14916     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
14917   Constant *C = ConstantInt::get(*Context, MaskElt);
14918   C = ConstantVector::getSplat(NumElts, C);
14919   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14920   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
14921   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14922   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14923                              MachinePointerInfo::getConstantPool(),
14924                              false, false, false, Alignment);
14925
14926   if (VT.isVector()) {
14927     // For a vector, cast operands to a vector type, perform the logic op,
14928     // and cast the result back to the original value type.
14929     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
14930     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
14931     SDValue Operand = IsFNABS ?
14932       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
14933       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
14934     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
14935     return DAG.getNode(ISD::BITCAST, dl, VT,
14936                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
14937   }
14938
14939   // If not vector, then scalar.
14940   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
14941   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
14942   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
14943 }
14944
14945 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
14946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14947   LLVMContext *Context = DAG.getContext();
14948   SDValue Op0 = Op.getOperand(0);
14949   SDValue Op1 = Op.getOperand(1);
14950   SDLoc dl(Op);
14951   MVT VT = Op.getSimpleValueType();
14952   MVT SrcVT = Op1.getSimpleValueType();
14953
14954   // If second operand is smaller, extend it first.
14955   if (SrcVT.bitsLT(VT)) {
14956     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
14957     SrcVT = VT;
14958   }
14959   // And if it is bigger, shrink it first.
14960   if (SrcVT.bitsGT(VT)) {
14961     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
14962     SrcVT = VT;
14963   }
14964
14965   // At this point the operands and the result should have the same
14966   // type, and that won't be f80 since that is not custom lowered.
14967
14968   const fltSemantics &Sem =
14969       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
14970   const unsigned SizeInBits = VT.getSizeInBits();
14971
14972   SmallVector<Constant *, 4> CV(
14973       VT == MVT::f64 ? 2 : 4,
14974       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
14975
14976   // First, clear all bits but the sign bit from the second operand (sign).
14977   CV[0] = ConstantFP::get(*Context,
14978                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
14979   Constant *C = ConstantVector::get(CV);
14980   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14981   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
14982                               MachinePointerInfo::getConstantPool(),
14983                               false, false, false, 16);
14984   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
14985
14986   // Next, clear the sign bit from the first operand (magnitude).
14987   // If it's a constant, we can clear it here.
14988   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
14989     APFloat APF = Op0CN->getValueAPF();
14990     // If the magnitude is a positive zero, the sign bit alone is enough.
14991     if (APF.isPosZero())
14992       return SignBit;
14993     APF.clearSign();
14994     CV[0] = ConstantFP::get(*Context, APF);
14995   } else {
14996     CV[0] = ConstantFP::get(
14997         *Context,
14998         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
14999   }
15000   C = ConstantVector::get(CV);
15001   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
15002   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
15003                             MachinePointerInfo::getConstantPool(),
15004                             false, false, false, 16);
15005   // If the magnitude operand wasn't a constant, we need to AND out the sign.
15006   if (!isa<ConstantFPSDNode>(Op0))
15007     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
15008
15009   // OR the magnitude value with the sign bit.
15010   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
15011 }
15012
15013 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
15014   SDValue N0 = Op.getOperand(0);
15015   SDLoc dl(Op);
15016   MVT VT = Op.getSimpleValueType();
15017
15018   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
15019   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
15020                                   DAG.getConstant(1, VT));
15021   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
15022 }
15023
15024 // Check whether an OR'd tree is PTEST-able.
15025 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
15026                                       SelectionDAG &DAG) {
15027   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
15028
15029   if (!Subtarget->hasSSE41())
15030     return SDValue();
15031
15032   if (!Op->hasOneUse())
15033     return SDValue();
15034
15035   SDNode *N = Op.getNode();
15036   SDLoc DL(N);
15037
15038   SmallVector<SDValue, 8> Opnds;
15039   DenseMap<SDValue, unsigned> VecInMap;
15040   SmallVector<SDValue, 8> VecIns;
15041   EVT VT = MVT::Other;
15042
15043   // Recognize a special case where a vector is casted into wide integer to
15044   // test all 0s.
15045   Opnds.push_back(N->getOperand(0));
15046   Opnds.push_back(N->getOperand(1));
15047
15048   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
15049     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
15050     // BFS traverse all OR'd operands.
15051     if (I->getOpcode() == ISD::OR) {
15052       Opnds.push_back(I->getOperand(0));
15053       Opnds.push_back(I->getOperand(1));
15054       // Re-evaluate the number of nodes to be traversed.
15055       e += 2; // 2 more nodes (LHS and RHS) are pushed.
15056       continue;
15057     }
15058
15059     // Quit if a non-EXTRACT_VECTOR_ELT
15060     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15061       return SDValue();
15062
15063     // Quit if without a constant index.
15064     SDValue Idx = I->getOperand(1);
15065     if (!isa<ConstantSDNode>(Idx))
15066       return SDValue();
15067
15068     SDValue ExtractedFromVec = I->getOperand(0);
15069     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
15070     if (M == VecInMap.end()) {
15071       VT = ExtractedFromVec.getValueType();
15072       // Quit if not 128/256-bit vector.
15073       if (!VT.is128BitVector() && !VT.is256BitVector())
15074         return SDValue();
15075       // Quit if not the same type.
15076       if (VecInMap.begin() != VecInMap.end() &&
15077           VT != VecInMap.begin()->first.getValueType())
15078         return SDValue();
15079       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
15080       VecIns.push_back(ExtractedFromVec);
15081     }
15082     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
15083   }
15084
15085   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15086          "Not extracted from 128-/256-bit vector.");
15087
15088   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
15089
15090   for (DenseMap<SDValue, unsigned>::const_iterator
15091         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
15092     // Quit if not all elements are used.
15093     if (I->second != FullMask)
15094       return SDValue();
15095   }
15096
15097   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
15098
15099   // Cast all vectors into TestVT for PTEST.
15100   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
15101     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
15102
15103   // If more than one full vectors are evaluated, OR them first before PTEST.
15104   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
15105     // Each iteration will OR 2 nodes and append the result until there is only
15106     // 1 node left, i.e. the final OR'd value of all vectors.
15107     SDValue LHS = VecIns[Slot];
15108     SDValue RHS = VecIns[Slot + 1];
15109     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
15110   }
15111
15112   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
15113                      VecIns.back(), VecIns.back());
15114 }
15115
15116 /// \brief return true if \c Op has a use that doesn't just read flags.
15117 static bool hasNonFlagsUse(SDValue Op) {
15118   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
15119        ++UI) {
15120     SDNode *User = *UI;
15121     unsigned UOpNo = UI.getOperandNo();
15122     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
15123       // Look pass truncate.
15124       UOpNo = User->use_begin().getOperandNo();
15125       User = *User->use_begin();
15126     }
15127
15128     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
15129         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
15130       return true;
15131   }
15132   return false;
15133 }
15134
15135 /// Emit nodes that will be selected as "test Op0,Op0", or something
15136 /// equivalent.
15137 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
15138                                     SelectionDAG &DAG) const {
15139   if (Op.getValueType() == MVT::i1) {
15140     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
15141     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
15142                        DAG.getConstant(0, MVT::i8));
15143   }
15144   // CF and OF aren't always set the way we want. Determine which
15145   // of these we need.
15146   bool NeedCF = false;
15147   bool NeedOF = false;
15148   switch (X86CC) {
15149   default: break;
15150   case X86::COND_A: case X86::COND_AE:
15151   case X86::COND_B: case X86::COND_BE:
15152     NeedCF = true;
15153     break;
15154   case X86::COND_G: case X86::COND_GE:
15155   case X86::COND_L: case X86::COND_LE:
15156   case X86::COND_O: case X86::COND_NO: {
15157     // Check if we really need to set the
15158     // Overflow flag. If NoSignedWrap is present
15159     // that is not actually needed.
15160     switch (Op->getOpcode()) {
15161     case ISD::ADD:
15162     case ISD::SUB:
15163     case ISD::MUL:
15164     case ISD::SHL: {
15165       const BinaryWithFlagsSDNode *BinNode =
15166           cast<BinaryWithFlagsSDNode>(Op.getNode());
15167       if (BinNode->hasNoSignedWrap())
15168         break;
15169     }
15170     default:
15171       NeedOF = true;
15172       break;
15173     }
15174     break;
15175   }
15176   }
15177   // See if we can use the EFLAGS value from the operand instead of
15178   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
15179   // we prove that the arithmetic won't overflow, we can't use OF or CF.
15180   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
15181     // Emit a CMP with 0, which is the TEST pattern.
15182     //if (Op.getValueType() == MVT::i1)
15183     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
15184     //                     DAG.getConstant(0, MVT::i1));
15185     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
15186                        DAG.getConstant(0, Op.getValueType()));
15187   }
15188   unsigned Opcode = 0;
15189   unsigned NumOperands = 0;
15190
15191   // Truncate operations may prevent the merge of the SETCC instruction
15192   // and the arithmetic instruction before it. Attempt to truncate the operands
15193   // of the arithmetic instruction and use a reduced bit-width instruction.
15194   bool NeedTruncation = false;
15195   SDValue ArithOp = Op;
15196   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
15197     SDValue Arith = Op->getOperand(0);
15198     // Both the trunc and the arithmetic op need to have one user each.
15199     if (Arith->hasOneUse())
15200       switch (Arith.getOpcode()) {
15201         default: break;
15202         case ISD::ADD:
15203         case ISD::SUB:
15204         case ISD::AND:
15205         case ISD::OR:
15206         case ISD::XOR: {
15207           NeedTruncation = true;
15208           ArithOp = Arith;
15209         }
15210       }
15211   }
15212
15213   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
15214   // which may be the result of a CAST.  We use the variable 'Op', which is the
15215   // non-casted variable when we check for possible users.
15216   switch (ArithOp.getOpcode()) {
15217   case ISD::ADD:
15218     // Due to an isel shortcoming, be conservative if this add is likely to be
15219     // selected as part of a load-modify-store instruction. When the root node
15220     // in a match is a store, isel doesn't know how to remap non-chain non-flag
15221     // uses of other nodes in the match, such as the ADD in this case. This
15222     // leads to the ADD being left around and reselected, with the result being
15223     // two adds in the output.  Alas, even if none our users are stores, that
15224     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
15225     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
15226     // climbing the DAG back to the root, and it doesn't seem to be worth the
15227     // effort.
15228     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15229          UE = Op.getNode()->use_end(); UI != UE; ++UI)
15230       if (UI->getOpcode() != ISD::CopyToReg &&
15231           UI->getOpcode() != ISD::SETCC &&
15232           UI->getOpcode() != ISD::STORE)
15233         goto default_case;
15234
15235     if (ConstantSDNode *C =
15236         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
15237       // An add of one will be selected as an INC.
15238       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
15239         Opcode = X86ISD::INC;
15240         NumOperands = 1;
15241         break;
15242       }
15243
15244       // An add of negative one (subtract of one) will be selected as a DEC.
15245       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
15246         Opcode = X86ISD::DEC;
15247         NumOperands = 1;
15248         break;
15249       }
15250     }
15251
15252     // Otherwise use a regular EFLAGS-setting add.
15253     Opcode = X86ISD::ADD;
15254     NumOperands = 2;
15255     break;
15256   case ISD::SHL:
15257   case ISD::SRL:
15258     // If we have a constant logical shift that's only used in a comparison
15259     // against zero turn it into an equivalent AND. This allows turning it into
15260     // a TEST instruction later.
15261     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
15262         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
15263       EVT VT = Op.getValueType();
15264       unsigned BitWidth = VT.getSizeInBits();
15265       unsigned ShAmt = Op->getConstantOperandVal(1);
15266       if (ShAmt >= BitWidth) // Avoid undefined shifts.
15267         break;
15268       APInt Mask = ArithOp.getOpcode() == ISD::SRL
15269                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
15270                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
15271       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
15272         break;
15273       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
15274                                 DAG.getConstant(Mask, VT));
15275       DAG.ReplaceAllUsesWith(Op, New);
15276       Op = New;
15277     }
15278     break;
15279
15280   case ISD::AND:
15281     // If the primary and result isn't used, don't bother using X86ISD::AND,
15282     // because a TEST instruction will be better.
15283     if (!hasNonFlagsUse(Op))
15284       break;
15285     // FALL THROUGH
15286   case ISD::SUB:
15287   case ISD::OR:
15288   case ISD::XOR:
15289     // Due to the ISEL shortcoming noted above, be conservative if this op is
15290     // likely to be selected as part of a load-modify-store instruction.
15291     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15292            UE = Op.getNode()->use_end(); UI != UE; ++UI)
15293       if (UI->getOpcode() == ISD::STORE)
15294         goto default_case;
15295
15296     // Otherwise use a regular EFLAGS-setting instruction.
15297     switch (ArithOp.getOpcode()) {
15298     default: llvm_unreachable("unexpected operator!");
15299     case ISD::SUB: Opcode = X86ISD::SUB; break;
15300     case ISD::XOR: Opcode = X86ISD::XOR; break;
15301     case ISD::AND: Opcode = X86ISD::AND; break;
15302     case ISD::OR: {
15303       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
15304         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
15305         if (EFLAGS.getNode())
15306           return EFLAGS;
15307       }
15308       Opcode = X86ISD::OR;
15309       break;
15310     }
15311     }
15312
15313     NumOperands = 2;
15314     break;
15315   case X86ISD::ADD:
15316   case X86ISD::SUB:
15317   case X86ISD::INC:
15318   case X86ISD::DEC:
15319   case X86ISD::OR:
15320   case X86ISD::XOR:
15321   case X86ISD::AND:
15322     return SDValue(Op.getNode(), 1);
15323   default:
15324   default_case:
15325     break;
15326   }
15327
15328   // If we found that truncation is beneficial, perform the truncation and
15329   // update 'Op'.
15330   if (NeedTruncation) {
15331     EVT VT = Op.getValueType();
15332     SDValue WideVal = Op->getOperand(0);
15333     EVT WideVT = WideVal.getValueType();
15334     unsigned ConvertedOp = 0;
15335     // Use a target machine opcode to prevent further DAGCombine
15336     // optimizations that may separate the arithmetic operations
15337     // from the setcc node.
15338     switch (WideVal.getOpcode()) {
15339       default: break;
15340       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
15341       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
15342       case ISD::AND: ConvertedOp = X86ISD::AND; break;
15343       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
15344       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
15345     }
15346
15347     if (ConvertedOp) {
15348       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15349       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
15350         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
15351         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
15352         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
15353       }
15354     }
15355   }
15356
15357   if (Opcode == 0)
15358     // Emit a CMP with 0, which is the TEST pattern.
15359     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
15360                        DAG.getConstant(0, Op.getValueType()));
15361
15362   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15363   SmallVector<SDValue, 4> Ops;
15364   for (unsigned i = 0; i != NumOperands; ++i)
15365     Ops.push_back(Op.getOperand(i));
15366
15367   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
15368   DAG.ReplaceAllUsesWith(Op, New);
15369   return SDValue(New.getNode(), 1);
15370 }
15371
15372 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
15373 /// equivalent.
15374 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
15375                                    SDLoc dl, SelectionDAG &DAG) const {
15376   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
15377     if (C->getAPIntValue() == 0)
15378       return EmitTest(Op0, X86CC, dl, DAG);
15379
15380      if (Op0.getValueType() == MVT::i1)
15381        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
15382   }
15383
15384   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
15385        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
15386     // Do the comparison at i32 if it's smaller, besides the Atom case.
15387     // This avoids subregister aliasing issues. Keep the smaller reference
15388     // if we're optimizing for size, however, as that'll allow better folding
15389     // of memory operations.
15390     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
15391         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
15392             Attribute::MinSize) &&
15393         !Subtarget->isAtom()) {
15394       unsigned ExtendOp =
15395           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
15396       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
15397       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
15398     }
15399     // Use SUB instead of CMP to enable CSE between SUB and CMP.
15400     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
15401     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
15402                               Op0, Op1);
15403     return SDValue(Sub.getNode(), 1);
15404   }
15405   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
15406 }
15407
15408 /// Convert a comparison if required by the subtarget.
15409 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
15410                                                  SelectionDAG &DAG) const {
15411   // If the subtarget does not support the FUCOMI instruction, floating-point
15412   // comparisons have to be converted.
15413   if (Subtarget->hasCMov() ||
15414       Cmp.getOpcode() != X86ISD::CMP ||
15415       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
15416       !Cmp.getOperand(1).getValueType().isFloatingPoint())
15417     return Cmp;
15418
15419   // The instruction selector will select an FUCOM instruction instead of
15420   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
15421   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
15422   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
15423   SDLoc dl(Cmp);
15424   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
15425   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
15426   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
15427                             DAG.getConstant(8, MVT::i8));
15428   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
15429   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
15430 }
15431
15432 /// The minimum architected relative accuracy is 2^-12. We need one
15433 /// Newton-Raphson step to have a good float result (24 bits of precision).
15434 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
15435                                             DAGCombinerInfo &DCI,
15436                                             unsigned &RefinementSteps,
15437                                             bool &UseOneConstNR) const {
15438   // FIXME: We should use instruction latency models to calculate the cost of
15439   // each potential sequence, but this is very hard to do reliably because
15440   // at least Intel's Core* chips have variable timing based on the number of
15441   // significant digits in the divisor and/or sqrt operand.
15442   if (!Subtarget->useSqrtEst())
15443     return SDValue();
15444
15445   EVT VT = Op.getValueType();
15446
15447   // SSE1 has rsqrtss and rsqrtps.
15448   // TODO: Add support for AVX512 (v16f32).
15449   // It is likely not profitable to do this for f64 because a double-precision
15450   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
15451   // instructions: convert to single, rsqrtss, convert back to double, refine
15452   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
15453   // along with FMA, this could be a throughput win.
15454   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
15455       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
15456     RefinementSteps = 1;
15457     UseOneConstNR = false;
15458     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
15459   }
15460   return SDValue();
15461 }
15462
15463 /// The minimum architected relative accuracy is 2^-12. We need one
15464 /// Newton-Raphson step to have a good float result (24 bits of precision).
15465 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
15466                                             DAGCombinerInfo &DCI,
15467                                             unsigned &RefinementSteps) const {
15468   // FIXME: We should use instruction latency models to calculate the cost of
15469   // each potential sequence, but this is very hard to do reliably because
15470   // at least Intel's Core* chips have variable timing based on the number of
15471   // significant digits in the divisor.
15472   if (!Subtarget->useReciprocalEst())
15473     return SDValue();
15474
15475   EVT VT = Op.getValueType();
15476
15477   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
15478   // TODO: Add support for AVX512 (v16f32).
15479   // It is likely not profitable to do this for f64 because a double-precision
15480   // reciprocal estimate with refinement on x86 prior to FMA requires
15481   // 15 instructions: convert to single, rcpss, convert back to double, refine
15482   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
15483   // along with FMA, this could be a throughput win.
15484   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
15485       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
15486     RefinementSteps = ReciprocalEstimateRefinementSteps;
15487     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
15488   }
15489   return SDValue();
15490 }
15491
15492 static bool isAllOnes(SDValue V) {
15493   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
15494   return C && C->isAllOnesValue();
15495 }
15496
15497 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
15498 /// if it's possible.
15499 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
15500                                      SDLoc dl, SelectionDAG &DAG) const {
15501   SDValue Op0 = And.getOperand(0);
15502   SDValue Op1 = And.getOperand(1);
15503   if (Op0.getOpcode() == ISD::TRUNCATE)
15504     Op0 = Op0.getOperand(0);
15505   if (Op1.getOpcode() == ISD::TRUNCATE)
15506     Op1 = Op1.getOperand(0);
15507
15508   SDValue LHS, RHS;
15509   if (Op1.getOpcode() == ISD::SHL)
15510     std::swap(Op0, Op1);
15511   if (Op0.getOpcode() == ISD::SHL) {
15512     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
15513       if (And00C->getZExtValue() == 1) {
15514         // If we looked past a truncate, check that it's only truncating away
15515         // known zeros.
15516         unsigned BitWidth = Op0.getValueSizeInBits();
15517         unsigned AndBitWidth = And.getValueSizeInBits();
15518         if (BitWidth > AndBitWidth) {
15519           APInt Zeros, Ones;
15520           DAG.computeKnownBits(Op0, Zeros, Ones);
15521           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
15522             return SDValue();
15523         }
15524         LHS = Op1;
15525         RHS = Op0.getOperand(1);
15526       }
15527   } else if (Op1.getOpcode() == ISD::Constant) {
15528     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
15529     uint64_t AndRHSVal = AndRHS->getZExtValue();
15530     SDValue AndLHS = Op0;
15531
15532     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
15533       LHS = AndLHS.getOperand(0);
15534       RHS = AndLHS.getOperand(1);
15535     }
15536
15537     // Use BT if the immediate can't be encoded in a TEST instruction.
15538     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
15539       LHS = AndLHS;
15540       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
15541     }
15542   }
15543
15544   if (LHS.getNode()) {
15545     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
15546     // instruction.  Since the shift amount is in-range-or-undefined, we know
15547     // that doing a bittest on the i32 value is ok.  We extend to i32 because
15548     // the encoding for the i16 version is larger than the i32 version.
15549     // Also promote i16 to i32 for performance / code size reason.
15550     if (LHS.getValueType() == MVT::i8 ||
15551         LHS.getValueType() == MVT::i16)
15552       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
15553
15554     // If the operand types disagree, extend the shift amount to match.  Since
15555     // BT ignores high bits (like shifts) we can use anyextend.
15556     if (LHS.getValueType() != RHS.getValueType())
15557       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
15558
15559     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
15560     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
15561     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15562                        DAG.getConstant(Cond, MVT::i8), BT);
15563   }
15564
15565   return SDValue();
15566 }
15567
15568 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
15569 /// mask CMPs.
15570 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
15571                               SDValue &Op1) {
15572   unsigned SSECC;
15573   bool Swap = false;
15574
15575   // SSE Condition code mapping:
15576   //  0 - EQ
15577   //  1 - LT
15578   //  2 - LE
15579   //  3 - UNORD
15580   //  4 - NEQ
15581   //  5 - NLT
15582   //  6 - NLE
15583   //  7 - ORD
15584   switch (SetCCOpcode) {
15585   default: llvm_unreachable("Unexpected SETCC condition");
15586   case ISD::SETOEQ:
15587   case ISD::SETEQ:  SSECC = 0; break;
15588   case ISD::SETOGT:
15589   case ISD::SETGT:  Swap = true; // Fallthrough
15590   case ISD::SETLT:
15591   case ISD::SETOLT: SSECC = 1; break;
15592   case ISD::SETOGE:
15593   case ISD::SETGE:  Swap = true; // Fallthrough
15594   case ISD::SETLE:
15595   case ISD::SETOLE: SSECC = 2; break;
15596   case ISD::SETUO:  SSECC = 3; break;
15597   case ISD::SETUNE:
15598   case ISD::SETNE:  SSECC = 4; break;
15599   case ISD::SETULE: Swap = true; // Fallthrough
15600   case ISD::SETUGE: SSECC = 5; break;
15601   case ISD::SETULT: Swap = true; // Fallthrough
15602   case ISD::SETUGT: SSECC = 6; break;
15603   case ISD::SETO:   SSECC = 7; break;
15604   case ISD::SETUEQ:
15605   case ISD::SETONE: SSECC = 8; break;
15606   }
15607   if (Swap)
15608     std::swap(Op0, Op1);
15609
15610   return SSECC;
15611 }
15612
15613 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
15614 // ones, and then concatenate the result back.
15615 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
15616   MVT VT = Op.getSimpleValueType();
15617
15618   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
15619          "Unsupported value type for operation");
15620
15621   unsigned NumElems = VT.getVectorNumElements();
15622   SDLoc dl(Op);
15623   SDValue CC = Op.getOperand(2);
15624
15625   // Extract the LHS vectors
15626   SDValue LHS = Op.getOperand(0);
15627   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15628   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15629
15630   // Extract the RHS vectors
15631   SDValue RHS = Op.getOperand(1);
15632   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15633   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15634
15635   // Issue the operation on the smaller types and concatenate the result back
15636   MVT EltVT = VT.getVectorElementType();
15637   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15638   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15639                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
15640                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
15641 }
15642
15643 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
15644                                      const X86Subtarget *Subtarget) {
15645   SDValue Op0 = Op.getOperand(0);
15646   SDValue Op1 = Op.getOperand(1);
15647   SDValue CC = Op.getOperand(2);
15648   MVT VT = Op.getSimpleValueType();
15649   SDLoc dl(Op);
15650
15651   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
15652          Op.getValueType().getScalarType() == MVT::i1 &&
15653          "Cannot set masked compare for this operation");
15654
15655   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15656   unsigned  Opc = 0;
15657   bool Unsigned = false;
15658   bool Swap = false;
15659   unsigned SSECC;
15660   switch (SetCCOpcode) {
15661   default: llvm_unreachable("Unexpected SETCC condition");
15662   case ISD::SETNE:  SSECC = 4; break;
15663   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
15664   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
15665   case ISD::SETLT:  Swap = true; //fall-through
15666   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
15667   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
15668   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
15669   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
15670   case ISD::SETULE: Unsigned = true; //fall-through
15671   case ISD::SETLE:  SSECC = 2; break;
15672   }
15673
15674   if (Swap)
15675     std::swap(Op0, Op1);
15676   if (Opc)
15677     return DAG.getNode(Opc, dl, VT, Op0, Op1);
15678   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
15679   return DAG.getNode(Opc, dl, VT, Op0, Op1,
15680                      DAG.getConstant(SSECC, MVT::i8));
15681 }
15682
15683 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
15684 /// operand \p Op1.  If non-trivial (for example because it's not constant)
15685 /// return an empty value.
15686 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
15687 {
15688   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
15689   if (!BV)
15690     return SDValue();
15691
15692   MVT VT = Op1.getSimpleValueType();
15693   MVT EVT = VT.getVectorElementType();
15694   unsigned n = VT.getVectorNumElements();
15695   SmallVector<SDValue, 8> ULTOp1;
15696
15697   for (unsigned i = 0; i < n; ++i) {
15698     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
15699     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
15700       return SDValue();
15701
15702     // Avoid underflow.
15703     APInt Val = Elt->getAPIntValue();
15704     if (Val == 0)
15705       return SDValue();
15706
15707     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
15708   }
15709
15710   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
15711 }
15712
15713 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
15714                            SelectionDAG &DAG) {
15715   SDValue Op0 = Op.getOperand(0);
15716   SDValue Op1 = Op.getOperand(1);
15717   SDValue CC = Op.getOperand(2);
15718   MVT VT = Op.getSimpleValueType();
15719   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15720   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
15721   SDLoc dl(Op);
15722
15723   if (isFP) {
15724 #ifndef NDEBUG
15725     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
15726     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
15727 #endif
15728
15729     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
15730     unsigned Opc = X86ISD::CMPP;
15731     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
15732       assert(VT.getVectorNumElements() <= 16);
15733       Opc = X86ISD::CMPM;
15734     }
15735     // In the two special cases we can't handle, emit two comparisons.
15736     if (SSECC == 8) {
15737       unsigned CC0, CC1;
15738       unsigned CombineOpc;
15739       if (SetCCOpcode == ISD::SETUEQ) {
15740         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
15741       } else {
15742         assert(SetCCOpcode == ISD::SETONE);
15743         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
15744       }
15745
15746       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15747                                  DAG.getConstant(CC0, MVT::i8));
15748       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15749                                  DAG.getConstant(CC1, MVT::i8));
15750       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
15751     }
15752     // Handle all other FP comparisons here.
15753     return DAG.getNode(Opc, dl, VT, Op0, Op1,
15754                        DAG.getConstant(SSECC, MVT::i8));
15755   }
15756
15757   // Break 256-bit integer vector compare into smaller ones.
15758   if (VT.is256BitVector() && !Subtarget->hasInt256())
15759     return Lower256IntVSETCC(Op, DAG);
15760
15761   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
15762   EVT OpVT = Op1.getValueType();
15763   if (Subtarget->hasAVX512()) {
15764     if (Op1.getValueType().is512BitVector() ||
15765         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
15766         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
15767       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
15768
15769     // In AVX-512 architecture setcc returns mask with i1 elements,
15770     // But there is no compare instruction for i8 and i16 elements in KNL.
15771     // We are not talking about 512-bit operands in this case, these
15772     // types are illegal.
15773     if (MaskResult &&
15774         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
15775          OpVT.getVectorElementType().getSizeInBits() >= 8))
15776       return DAG.getNode(ISD::TRUNCATE, dl, VT,
15777                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
15778   }
15779
15780   // We are handling one of the integer comparisons here.  Since SSE only has
15781   // GT and EQ comparisons for integer, swapping operands and multiple
15782   // operations may be required for some comparisons.
15783   unsigned Opc;
15784   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
15785   bool Subus = false;
15786
15787   switch (SetCCOpcode) {
15788   default: llvm_unreachable("Unexpected SETCC condition");
15789   case ISD::SETNE:  Invert = true;
15790   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
15791   case ISD::SETLT:  Swap = true;
15792   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
15793   case ISD::SETGE:  Swap = true;
15794   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
15795                     Invert = true; break;
15796   case ISD::SETULT: Swap = true;
15797   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
15798                     FlipSigns = true; break;
15799   case ISD::SETUGE: Swap = true;
15800   case ISD::SETULE: Opc = X86ISD::PCMPGT;
15801                     FlipSigns = true; Invert = true; break;
15802   }
15803
15804   // Special case: Use min/max operations for SETULE/SETUGE
15805   MVT VET = VT.getVectorElementType();
15806   bool hasMinMax =
15807        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
15808     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
15809
15810   if (hasMinMax) {
15811     switch (SetCCOpcode) {
15812     default: break;
15813     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
15814     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
15815     }
15816
15817     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
15818   }
15819
15820   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
15821   if (!MinMax && hasSubus) {
15822     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
15823     // Op0 u<= Op1:
15824     //   t = psubus Op0, Op1
15825     //   pcmpeq t, <0..0>
15826     switch (SetCCOpcode) {
15827     default: break;
15828     case ISD::SETULT: {
15829       // If the comparison is against a constant we can turn this into a
15830       // setule.  With psubus, setule does not require a swap.  This is
15831       // beneficial because the constant in the register is no longer
15832       // destructed as the destination so it can be hoisted out of a loop.
15833       // Only do this pre-AVX since vpcmp* is no longer destructive.
15834       if (Subtarget->hasAVX())
15835         break;
15836       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
15837       if (ULEOp1.getNode()) {
15838         Op1 = ULEOp1;
15839         Subus = true; Invert = false; Swap = false;
15840       }
15841       break;
15842     }
15843     // Psubus is better than flip-sign because it requires no inversion.
15844     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
15845     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
15846     }
15847
15848     if (Subus) {
15849       Opc = X86ISD::SUBUS;
15850       FlipSigns = false;
15851     }
15852   }
15853
15854   if (Swap)
15855     std::swap(Op0, Op1);
15856
15857   // Check that the operation in question is available (most are plain SSE2,
15858   // but PCMPGTQ and PCMPEQQ have different requirements).
15859   if (VT == MVT::v2i64) {
15860     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
15861       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
15862
15863       // First cast everything to the right type.
15864       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15865       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15866
15867       // Since SSE has no unsigned integer comparisons, we need to flip the sign
15868       // bits of the inputs before performing those operations. The lower
15869       // compare is always unsigned.
15870       SDValue SB;
15871       if (FlipSigns) {
15872         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
15873       } else {
15874         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
15875         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
15876         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
15877                          Sign, Zero, Sign, Zero);
15878       }
15879       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
15880       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
15881
15882       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
15883       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
15884       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
15885
15886       // Create masks for only the low parts/high parts of the 64 bit integers.
15887       static const int MaskHi[] = { 1, 1, 3, 3 };
15888       static const int MaskLo[] = { 0, 0, 2, 2 };
15889       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
15890       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
15891       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
15892
15893       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
15894       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
15895
15896       if (Invert)
15897         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15898
15899       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15900     }
15901
15902     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
15903       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
15904       // pcmpeqd + pshufd + pand.
15905       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
15906
15907       // First cast everything to the right type.
15908       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15909       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15910
15911       // Do the compare.
15912       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
15913
15914       // Make sure the lower and upper halves are both all-ones.
15915       static const int Mask[] = { 1, 0, 3, 2 };
15916       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
15917       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
15918
15919       if (Invert)
15920         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15921
15922       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15923     }
15924   }
15925
15926   // Since SSE has no unsigned integer comparisons, we need to flip the sign
15927   // bits of the inputs before performing those operations.
15928   if (FlipSigns) {
15929     EVT EltVT = VT.getVectorElementType();
15930     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
15931     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
15932     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
15933   }
15934
15935   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
15936
15937   // If the logical-not of the result is required, perform that now.
15938   if (Invert)
15939     Result = DAG.getNOT(dl, Result, VT);
15940
15941   if (MinMax)
15942     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
15943
15944   if (Subus)
15945     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
15946                          getZeroVector(VT, Subtarget, DAG, dl));
15947
15948   return Result;
15949 }
15950
15951 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
15952
15953   MVT VT = Op.getSimpleValueType();
15954
15955   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
15956
15957   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
15958          && "SetCC type must be 8-bit or 1-bit integer");
15959   SDValue Op0 = Op.getOperand(0);
15960   SDValue Op1 = Op.getOperand(1);
15961   SDLoc dl(Op);
15962   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
15963
15964   // Optimize to BT if possible.
15965   // Lower (X & (1 << N)) == 0 to BT(X, N).
15966   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
15967   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
15968   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
15969       Op1.getOpcode() == ISD::Constant &&
15970       cast<ConstantSDNode>(Op1)->isNullValue() &&
15971       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15972     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
15973     if (NewSetCC.getNode()) {
15974       if (VT == MVT::i1)
15975         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
15976       return NewSetCC;
15977     }
15978   }
15979
15980   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
15981   // these.
15982   if (Op1.getOpcode() == ISD::Constant &&
15983       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
15984        cast<ConstantSDNode>(Op1)->isNullValue()) &&
15985       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15986
15987     // If the input is a setcc, then reuse the input setcc or use a new one with
15988     // the inverted condition.
15989     if (Op0.getOpcode() == X86ISD::SETCC) {
15990       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
15991       bool Invert = (CC == ISD::SETNE) ^
15992         cast<ConstantSDNode>(Op1)->isNullValue();
15993       if (!Invert)
15994         return Op0;
15995
15996       CCode = X86::GetOppositeBranchCondition(CCode);
15997       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15998                                   DAG.getConstant(CCode, MVT::i8),
15999                                   Op0.getOperand(1));
16000       if (VT == MVT::i1)
16001         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
16002       return SetCC;
16003     }
16004   }
16005   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
16006       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
16007       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
16008
16009     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
16010     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
16011   }
16012
16013   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
16014   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
16015   if (X86CC == X86::COND_INVALID)
16016     return SDValue();
16017
16018   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
16019   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
16020   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16021                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
16022   if (VT == MVT::i1)
16023     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
16024   return SetCC;
16025 }
16026
16027 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
16028 static bool isX86LogicalCmp(SDValue Op) {
16029   unsigned Opc = Op.getNode()->getOpcode();
16030   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
16031       Opc == X86ISD::SAHF)
16032     return true;
16033   if (Op.getResNo() == 1 &&
16034       (Opc == X86ISD::ADD ||
16035        Opc == X86ISD::SUB ||
16036        Opc == X86ISD::ADC ||
16037        Opc == X86ISD::SBB ||
16038        Opc == X86ISD::SMUL ||
16039        Opc == X86ISD::UMUL ||
16040        Opc == X86ISD::INC ||
16041        Opc == X86ISD::DEC ||
16042        Opc == X86ISD::OR ||
16043        Opc == X86ISD::XOR ||
16044        Opc == X86ISD::AND))
16045     return true;
16046
16047   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
16048     return true;
16049
16050   return false;
16051 }
16052
16053 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
16054   if (V.getOpcode() != ISD::TRUNCATE)
16055     return false;
16056
16057   SDValue VOp0 = V.getOperand(0);
16058   unsigned InBits = VOp0.getValueSizeInBits();
16059   unsigned Bits = V.getValueSizeInBits();
16060   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
16061 }
16062
16063 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
16064   bool addTest = true;
16065   SDValue Cond  = Op.getOperand(0);
16066   SDValue Op1 = Op.getOperand(1);
16067   SDValue Op2 = Op.getOperand(2);
16068   SDLoc DL(Op);
16069   EVT VT = Op1.getValueType();
16070   SDValue CC;
16071
16072   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
16073   // are available. Otherwise fp cmovs get lowered into a less efficient branch
16074   // sequence later on.
16075   if (Cond.getOpcode() == ISD::SETCC &&
16076       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
16077        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
16078       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
16079     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
16080     int SSECC = translateX86FSETCC(
16081         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
16082
16083     if (SSECC != 8) {
16084       if (Subtarget->hasAVX512()) {
16085         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
16086                                   DAG.getConstant(SSECC, MVT::i8));
16087         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
16088       }
16089       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
16090                                 DAG.getConstant(SSECC, MVT::i8));
16091       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
16092       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
16093       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
16094     }
16095   }
16096
16097   if (Cond.getOpcode() == ISD::SETCC) {
16098     SDValue NewCond = LowerSETCC(Cond, DAG);
16099     if (NewCond.getNode())
16100       Cond = NewCond;
16101   }
16102
16103   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
16104   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
16105   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
16106   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
16107   if (Cond.getOpcode() == X86ISD::SETCC &&
16108       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
16109       isZero(Cond.getOperand(1).getOperand(1))) {
16110     SDValue Cmp = Cond.getOperand(1);
16111
16112     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
16113
16114     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
16115         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
16116       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
16117
16118       SDValue CmpOp0 = Cmp.getOperand(0);
16119       // Apply further optimizations for special cases
16120       // (select (x != 0), -1, 0) -> neg & sbb
16121       // (select (x == 0), 0, -1) -> neg & sbb
16122       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
16123         if (YC->isNullValue() &&
16124             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
16125           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
16126           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
16127                                     DAG.getConstant(0, CmpOp0.getValueType()),
16128                                     CmpOp0);
16129           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
16130                                     DAG.getConstant(X86::COND_B, MVT::i8),
16131                                     SDValue(Neg.getNode(), 1));
16132           return Res;
16133         }
16134
16135       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
16136                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
16137       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16138
16139       SDValue Res =   // Res = 0 or -1.
16140         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
16141                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
16142
16143       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
16144         Res = DAG.getNOT(DL, Res, Res.getValueType());
16145
16146       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
16147       if (!N2C || !N2C->isNullValue())
16148         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
16149       return Res;
16150     }
16151   }
16152
16153   // Look past (and (setcc_carry (cmp ...)), 1).
16154   if (Cond.getOpcode() == ISD::AND &&
16155       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
16156     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
16157     if (C && C->getAPIntValue() == 1)
16158       Cond = Cond.getOperand(0);
16159   }
16160
16161   // If condition flag is set by a X86ISD::CMP, then use it as the condition
16162   // setting operand in place of the X86ISD::SETCC.
16163   unsigned CondOpcode = Cond.getOpcode();
16164   if (CondOpcode == X86ISD::SETCC ||
16165       CondOpcode == X86ISD::SETCC_CARRY) {
16166     CC = Cond.getOperand(0);
16167
16168     SDValue Cmp = Cond.getOperand(1);
16169     unsigned Opc = Cmp.getOpcode();
16170     MVT VT = Op.getSimpleValueType();
16171
16172     bool IllegalFPCMov = false;
16173     if (VT.isFloatingPoint() && !VT.isVector() &&
16174         !isScalarFPTypeInSSEReg(VT))  // FPStack?
16175       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
16176
16177     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
16178         Opc == X86ISD::BT) { // FIXME
16179       Cond = Cmp;
16180       addTest = false;
16181     }
16182   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
16183              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
16184              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
16185               Cond.getOperand(0).getValueType() != MVT::i8)) {
16186     SDValue LHS = Cond.getOperand(0);
16187     SDValue RHS = Cond.getOperand(1);
16188     unsigned X86Opcode;
16189     unsigned X86Cond;
16190     SDVTList VTs;
16191     switch (CondOpcode) {
16192     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
16193     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
16194     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
16195     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
16196     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
16197     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
16198     default: llvm_unreachable("unexpected overflowing operator");
16199     }
16200     if (CondOpcode == ISD::UMULO)
16201       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
16202                           MVT::i32);
16203     else
16204       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
16205
16206     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
16207
16208     if (CondOpcode == ISD::UMULO)
16209       Cond = X86Op.getValue(2);
16210     else
16211       Cond = X86Op.getValue(1);
16212
16213     CC = DAG.getConstant(X86Cond, MVT::i8);
16214     addTest = false;
16215   }
16216
16217   if (addTest) {
16218     // Look pass the truncate if the high bits are known zero.
16219     if (isTruncWithZeroHighBitsInput(Cond, DAG))
16220         Cond = Cond.getOperand(0);
16221
16222     // We know the result of AND is compared against zero. Try to match
16223     // it to BT.
16224     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16225       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
16226       if (NewSetCC.getNode()) {
16227         CC = NewSetCC.getOperand(0);
16228         Cond = NewSetCC.getOperand(1);
16229         addTest = false;
16230       }
16231     }
16232   }
16233
16234   if (addTest) {
16235     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16236     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
16237   }
16238
16239   // a <  b ? -1 :  0 -> RES = ~setcc_carry
16240   // a <  b ?  0 : -1 -> RES = setcc_carry
16241   // a >= b ? -1 :  0 -> RES = setcc_carry
16242   // a >= b ?  0 : -1 -> RES = ~setcc_carry
16243   if (Cond.getOpcode() == X86ISD::SUB) {
16244     Cond = ConvertCmpIfNecessary(Cond, DAG);
16245     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
16246
16247     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
16248         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
16249       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
16250                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
16251       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
16252         return DAG.getNOT(DL, Res, Res.getValueType());
16253       return Res;
16254     }
16255   }
16256
16257   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
16258   // widen the cmov and push the truncate through. This avoids introducing a new
16259   // branch during isel and doesn't add any extensions.
16260   if (Op.getValueType() == MVT::i8 &&
16261       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
16262     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
16263     if (T1.getValueType() == T2.getValueType() &&
16264         // Blacklist CopyFromReg to avoid partial register stalls.
16265         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
16266       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
16267       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
16268       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
16269     }
16270   }
16271
16272   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
16273   // condition is true.
16274   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
16275   SDValue Ops[] = { Op2, Op1, CC, Cond };
16276   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
16277 }
16278
16279 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
16280                                        SelectionDAG &DAG) {
16281   MVT VT = Op->getSimpleValueType(0);
16282   SDValue In = Op->getOperand(0);
16283   MVT InVT = In.getSimpleValueType();
16284   MVT VTElt = VT.getVectorElementType();
16285   MVT InVTElt = InVT.getVectorElementType();
16286   SDLoc dl(Op);
16287
16288   // SKX processor
16289   if ((InVTElt == MVT::i1) &&
16290       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
16291         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
16292
16293        ((Subtarget->hasBWI() && VT.is512BitVector() &&
16294         VTElt.getSizeInBits() <= 16)) ||
16295
16296        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
16297         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
16298
16299        ((Subtarget->hasDQI() && VT.is512BitVector() &&
16300         VTElt.getSizeInBits() >= 32))))
16301     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
16302
16303   unsigned int NumElts = VT.getVectorNumElements();
16304
16305   if (NumElts != 8 && NumElts != 16)
16306     return SDValue();
16307
16308   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
16309     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
16310       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
16311     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
16312   }
16313
16314   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16315   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
16316
16317   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
16318   Constant *C = ConstantInt::get(*DAG.getContext(),
16319     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
16320
16321   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
16322   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
16323   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
16324                           MachinePointerInfo::getConstantPool(),
16325                           false, false, false, Alignment);
16326   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
16327   if (VT.is512BitVector())
16328     return Brcst;
16329   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
16330 }
16331
16332 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
16333                                 SelectionDAG &DAG) {
16334   MVT VT = Op->getSimpleValueType(0);
16335   SDValue In = Op->getOperand(0);
16336   MVT InVT = In.getSimpleValueType();
16337   SDLoc dl(Op);
16338
16339   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
16340     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
16341
16342   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
16343       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
16344       (VT != MVT::v16i16 || InVT != MVT::v16i8))
16345     return SDValue();
16346
16347   if (Subtarget->hasInt256())
16348     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
16349
16350   // Optimize vectors in AVX mode
16351   // Sign extend  v8i16 to v8i32 and
16352   //              v4i32 to v4i64
16353   //
16354   // Divide input vector into two parts
16355   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16356   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16357   // concat the vectors to original VT
16358
16359   unsigned NumElems = InVT.getVectorNumElements();
16360   SDValue Undef = DAG.getUNDEF(InVT);
16361
16362   SmallVector<int,8> ShufMask1(NumElems, -1);
16363   for (unsigned i = 0; i != NumElems/2; ++i)
16364     ShufMask1[i] = i;
16365
16366   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
16367
16368   SmallVector<int,8> ShufMask2(NumElems, -1);
16369   for (unsigned i = 0; i != NumElems/2; ++i)
16370     ShufMask2[i] = i + NumElems/2;
16371
16372   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
16373
16374   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
16375                                 VT.getVectorNumElements()/2);
16376
16377   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
16378   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
16379
16380   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16381 }
16382
16383 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
16384 // may emit an illegal shuffle but the expansion is still better than scalar
16385 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
16386 // we'll emit a shuffle and a arithmetic shift.
16387 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
16388 // TODO: It is possible to support ZExt by zeroing the undef values during
16389 // the shuffle phase or after the shuffle.
16390 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
16391                                  SelectionDAG &DAG) {
16392   MVT RegVT = Op.getSimpleValueType();
16393   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
16394   assert(RegVT.isInteger() &&
16395          "We only custom lower integer vector sext loads.");
16396
16397   // Nothing useful we can do without SSE2 shuffles.
16398   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
16399
16400   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
16401   SDLoc dl(Ld);
16402   EVT MemVT = Ld->getMemoryVT();
16403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16404   unsigned RegSz = RegVT.getSizeInBits();
16405
16406   ISD::LoadExtType Ext = Ld->getExtensionType();
16407
16408   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
16409          && "Only anyext and sext are currently implemented.");
16410   assert(MemVT != RegVT && "Cannot extend to the same type");
16411   assert(MemVT.isVector() && "Must load a vector from memory");
16412
16413   unsigned NumElems = RegVT.getVectorNumElements();
16414   unsigned MemSz = MemVT.getSizeInBits();
16415   assert(RegSz > MemSz && "Register size must be greater than the mem size");
16416
16417   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
16418     // The only way in which we have a legal 256-bit vector result but not the
16419     // integer 256-bit operations needed to directly lower a sextload is if we
16420     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
16421     // a 128-bit vector and a normal sign_extend to 256-bits that should get
16422     // correctly legalized. We do this late to allow the canonical form of
16423     // sextload to persist throughout the rest of the DAG combiner -- it wants
16424     // to fold together any extensions it can, and so will fuse a sign_extend
16425     // of an sextload into a sextload targeting a wider value.
16426     SDValue Load;
16427     if (MemSz == 128) {
16428       // Just switch this to a normal load.
16429       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
16430                                        "it must be a legal 128-bit vector "
16431                                        "type!");
16432       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
16433                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
16434                   Ld->isInvariant(), Ld->getAlignment());
16435     } else {
16436       assert(MemSz < 128 &&
16437              "Can't extend a type wider than 128 bits to a 256 bit vector!");
16438       // Do an sext load to a 128-bit vector type. We want to use the same
16439       // number of elements, but elements half as wide. This will end up being
16440       // recursively lowered by this routine, but will succeed as we definitely
16441       // have all the necessary features if we're using AVX1.
16442       EVT HalfEltVT =
16443           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
16444       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
16445       Load =
16446           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
16447                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
16448                          Ld->isNonTemporal(), Ld->isInvariant(),
16449                          Ld->getAlignment());
16450     }
16451
16452     // Replace chain users with the new chain.
16453     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
16454     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
16455
16456     // Finally, do a normal sign-extend to the desired register.
16457     return DAG.getSExtOrTrunc(Load, dl, RegVT);
16458   }
16459
16460   // All sizes must be a power of two.
16461   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
16462          "Non-power-of-two elements are not custom lowered!");
16463
16464   // Attempt to load the original value using scalar loads.
16465   // Find the largest scalar type that divides the total loaded size.
16466   MVT SclrLoadTy = MVT::i8;
16467   for (MVT Tp : MVT::integer_valuetypes()) {
16468     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16469       SclrLoadTy = Tp;
16470     }
16471   }
16472
16473   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16474   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16475       (64 <= MemSz))
16476     SclrLoadTy = MVT::f64;
16477
16478   // Calculate the number of scalar loads that we need to perform
16479   // in order to load our vector from memory.
16480   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16481
16482   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
16483          "Can only lower sext loads with a single scalar load!");
16484
16485   unsigned loadRegZize = RegSz;
16486   if (Ext == ISD::SEXTLOAD && RegSz == 256)
16487     loadRegZize /= 2;
16488
16489   // Represent our vector as a sequence of elements which are the
16490   // largest scalar that we can load.
16491   EVT LoadUnitVecVT = EVT::getVectorVT(
16492       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
16493
16494   // Represent the data using the same element type that is stored in
16495   // memory. In practice, we ''widen'' MemVT.
16496   EVT WideVecVT =
16497       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16498                        loadRegZize / MemVT.getScalarType().getSizeInBits());
16499
16500   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16501          "Invalid vector type");
16502
16503   // We can't shuffle using an illegal type.
16504   assert(TLI.isTypeLegal(WideVecVT) &&
16505          "We only lower types that form legal widened vector types");
16506
16507   SmallVector<SDValue, 8> Chains;
16508   SDValue Ptr = Ld->getBasePtr();
16509   SDValue Increment =
16510       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
16511   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16512
16513   for (unsigned i = 0; i < NumLoads; ++i) {
16514     // Perform a single load.
16515     SDValue ScalarLoad =
16516         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
16517                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
16518                     Ld->getAlignment());
16519     Chains.push_back(ScalarLoad.getValue(1));
16520     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16521     // another round of DAGCombining.
16522     if (i == 0)
16523       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16524     else
16525       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16526                         ScalarLoad, DAG.getIntPtrConstant(i));
16527
16528     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16529   }
16530
16531   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
16532
16533   // Bitcast the loaded value to a vector of the original element type, in
16534   // the size of the target vector type.
16535   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16536   unsigned SizeRatio = RegSz / MemSz;
16537
16538   if (Ext == ISD::SEXTLOAD) {
16539     // If we have SSE4.1, we can directly emit a VSEXT node.
16540     if (Subtarget->hasSSE41()) {
16541       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16542       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16543       return Sext;
16544     }
16545
16546     // Otherwise we'll shuffle the small elements in the high bits of the
16547     // larger type and perform an arithmetic shift. If the shift is not legal
16548     // it's better to scalarize.
16549     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
16550            "We can't implement a sext load without an arithmetic right shift!");
16551
16552     // Redistribute the loaded elements into the different locations.
16553     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16554     for (unsigned i = 0; i != NumElems; ++i)
16555       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
16556
16557     SDValue Shuff = DAG.getVectorShuffle(
16558         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16559
16560     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16561
16562     // Build the arithmetic shift.
16563     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16564                    MemVT.getVectorElementType().getSizeInBits();
16565     Shuff =
16566         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
16567
16568     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16569     return Shuff;
16570   }
16571
16572   // Redistribute the loaded elements into the different locations.
16573   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16574   for (unsigned i = 0; i != NumElems; ++i)
16575     ShuffleVec[i * SizeRatio] = i;
16576
16577   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16578                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16579
16580   // Bitcast to the requested type.
16581   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16582   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16583   return Shuff;
16584 }
16585
16586 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
16587 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
16588 // from the AND / OR.
16589 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
16590   Opc = Op.getOpcode();
16591   if (Opc != ISD::OR && Opc != ISD::AND)
16592     return false;
16593   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16594           Op.getOperand(0).hasOneUse() &&
16595           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
16596           Op.getOperand(1).hasOneUse());
16597 }
16598
16599 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
16600 // 1 and that the SETCC node has a single use.
16601 static bool isXor1OfSetCC(SDValue Op) {
16602   if (Op.getOpcode() != ISD::XOR)
16603     return false;
16604   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16605   if (N1C && N1C->getAPIntValue() == 1) {
16606     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16607       Op.getOperand(0).hasOneUse();
16608   }
16609   return false;
16610 }
16611
16612 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
16613   bool addTest = true;
16614   SDValue Chain = Op.getOperand(0);
16615   SDValue Cond  = Op.getOperand(1);
16616   SDValue Dest  = Op.getOperand(2);
16617   SDLoc dl(Op);
16618   SDValue CC;
16619   bool Inverted = false;
16620
16621   if (Cond.getOpcode() == ISD::SETCC) {
16622     // Check for setcc([su]{add,sub,mul}o == 0).
16623     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
16624         isa<ConstantSDNode>(Cond.getOperand(1)) &&
16625         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
16626         Cond.getOperand(0).getResNo() == 1 &&
16627         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
16628          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
16629          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
16630          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
16631          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
16632          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
16633       Inverted = true;
16634       Cond = Cond.getOperand(0);
16635     } else {
16636       SDValue NewCond = LowerSETCC(Cond, DAG);
16637       if (NewCond.getNode())
16638         Cond = NewCond;
16639     }
16640   }
16641 #if 0
16642   // FIXME: LowerXALUO doesn't handle these!!
16643   else if (Cond.getOpcode() == X86ISD::ADD  ||
16644            Cond.getOpcode() == X86ISD::SUB  ||
16645            Cond.getOpcode() == X86ISD::SMUL ||
16646            Cond.getOpcode() == X86ISD::UMUL)
16647     Cond = LowerXALUO(Cond, DAG);
16648 #endif
16649
16650   // Look pass (and (setcc_carry (cmp ...)), 1).
16651   if (Cond.getOpcode() == ISD::AND &&
16652       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
16653     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
16654     if (C && C->getAPIntValue() == 1)
16655       Cond = Cond.getOperand(0);
16656   }
16657
16658   // If condition flag is set by a X86ISD::CMP, then use it as the condition
16659   // setting operand in place of the X86ISD::SETCC.
16660   unsigned CondOpcode = Cond.getOpcode();
16661   if (CondOpcode == X86ISD::SETCC ||
16662       CondOpcode == X86ISD::SETCC_CARRY) {
16663     CC = Cond.getOperand(0);
16664
16665     SDValue Cmp = Cond.getOperand(1);
16666     unsigned Opc = Cmp.getOpcode();
16667     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
16668     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
16669       Cond = Cmp;
16670       addTest = false;
16671     } else {
16672       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
16673       default: break;
16674       case X86::COND_O:
16675       case X86::COND_B:
16676         // These can only come from an arithmetic instruction with overflow,
16677         // e.g. SADDO, UADDO.
16678         Cond = Cond.getNode()->getOperand(1);
16679         addTest = false;
16680         break;
16681       }
16682     }
16683   }
16684   CondOpcode = Cond.getOpcode();
16685   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
16686       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
16687       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
16688        Cond.getOperand(0).getValueType() != MVT::i8)) {
16689     SDValue LHS = Cond.getOperand(0);
16690     SDValue RHS = Cond.getOperand(1);
16691     unsigned X86Opcode;
16692     unsigned X86Cond;
16693     SDVTList VTs;
16694     // Keep this in sync with LowerXALUO, otherwise we might create redundant
16695     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
16696     // X86ISD::INC).
16697     switch (CondOpcode) {
16698     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
16699     case ISD::SADDO:
16700       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16701         if (C->isOne()) {
16702           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
16703           break;
16704         }
16705       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
16706     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
16707     case ISD::SSUBO:
16708       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16709         if (C->isOne()) {
16710           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
16711           break;
16712         }
16713       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
16714     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
16715     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
16716     default: llvm_unreachable("unexpected overflowing operator");
16717     }
16718     if (Inverted)
16719       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
16720     if (CondOpcode == ISD::UMULO)
16721       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
16722                           MVT::i32);
16723     else
16724       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
16725
16726     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
16727
16728     if (CondOpcode == ISD::UMULO)
16729       Cond = X86Op.getValue(2);
16730     else
16731       Cond = X86Op.getValue(1);
16732
16733     CC = DAG.getConstant(X86Cond, MVT::i8);
16734     addTest = false;
16735   } else {
16736     unsigned CondOpc;
16737     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
16738       SDValue Cmp = Cond.getOperand(0).getOperand(1);
16739       if (CondOpc == ISD::OR) {
16740         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
16741         // two branches instead of an explicit OR instruction with a
16742         // separate test.
16743         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16744             isX86LogicalCmp(Cmp)) {
16745           CC = Cond.getOperand(0).getOperand(0);
16746           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16747                               Chain, Dest, CC, Cmp);
16748           CC = Cond.getOperand(1).getOperand(0);
16749           Cond = Cmp;
16750           addTest = false;
16751         }
16752       } else { // ISD::AND
16753         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
16754         // two branches instead of an explicit AND instruction with a
16755         // separate test. However, we only do this if this block doesn't
16756         // have a fall-through edge, because this requires an explicit
16757         // jmp when the condition is false.
16758         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16759             isX86LogicalCmp(Cmp) &&
16760             Op.getNode()->hasOneUse()) {
16761           X86::CondCode CCode =
16762             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16763           CCode = X86::GetOppositeBranchCondition(CCode);
16764           CC = DAG.getConstant(CCode, MVT::i8);
16765           SDNode *User = *Op.getNode()->use_begin();
16766           // Look for an unconditional branch following this conditional branch.
16767           // We need this because we need to reverse the successors in order
16768           // to implement FCMP_OEQ.
16769           if (User->getOpcode() == ISD::BR) {
16770             SDValue FalseBB = User->getOperand(1);
16771             SDNode *NewBR =
16772               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16773             assert(NewBR == User);
16774             (void)NewBR;
16775             Dest = FalseBB;
16776
16777             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16778                                 Chain, Dest, CC, Cmp);
16779             X86::CondCode CCode =
16780               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
16781             CCode = X86::GetOppositeBranchCondition(CCode);
16782             CC = DAG.getConstant(CCode, MVT::i8);
16783             Cond = Cmp;
16784             addTest = false;
16785           }
16786         }
16787       }
16788     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
16789       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
16790       // It should be transformed during dag combiner except when the condition
16791       // is set by a arithmetics with overflow node.
16792       X86::CondCode CCode =
16793         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16794       CCode = X86::GetOppositeBranchCondition(CCode);
16795       CC = DAG.getConstant(CCode, MVT::i8);
16796       Cond = Cond.getOperand(0).getOperand(1);
16797       addTest = false;
16798     } else if (Cond.getOpcode() == ISD::SETCC &&
16799                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
16800       // For FCMP_OEQ, we can emit
16801       // two branches instead of an explicit AND instruction with a
16802       // separate test. However, we only do this if this block doesn't
16803       // have a fall-through edge, because this requires an explicit
16804       // jmp when the condition is false.
16805       if (Op.getNode()->hasOneUse()) {
16806         SDNode *User = *Op.getNode()->use_begin();
16807         // Look for an unconditional branch following this conditional branch.
16808         // We need this because we need to reverse the successors in order
16809         // to implement FCMP_OEQ.
16810         if (User->getOpcode() == ISD::BR) {
16811           SDValue FalseBB = User->getOperand(1);
16812           SDNode *NewBR =
16813             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16814           assert(NewBR == User);
16815           (void)NewBR;
16816           Dest = FalseBB;
16817
16818           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16819                                     Cond.getOperand(0), Cond.getOperand(1));
16820           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16821           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16822           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16823                               Chain, Dest, CC, Cmp);
16824           CC = DAG.getConstant(X86::COND_P, MVT::i8);
16825           Cond = Cmp;
16826           addTest = false;
16827         }
16828       }
16829     } else if (Cond.getOpcode() == ISD::SETCC &&
16830                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
16831       // For FCMP_UNE, we can emit
16832       // two branches instead of an explicit AND instruction with a
16833       // separate test. However, we only do this if this block doesn't
16834       // have a fall-through edge, because this requires an explicit
16835       // jmp when the condition is false.
16836       if (Op.getNode()->hasOneUse()) {
16837         SDNode *User = *Op.getNode()->use_begin();
16838         // Look for an unconditional branch following this conditional branch.
16839         // We need this because we need to reverse the successors in order
16840         // to implement FCMP_UNE.
16841         if (User->getOpcode() == ISD::BR) {
16842           SDValue FalseBB = User->getOperand(1);
16843           SDNode *NewBR =
16844             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16845           assert(NewBR == User);
16846           (void)NewBR;
16847
16848           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16849                                     Cond.getOperand(0), Cond.getOperand(1));
16850           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16851           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16852           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16853                               Chain, Dest, CC, Cmp);
16854           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
16855           Cond = Cmp;
16856           addTest = false;
16857           Dest = FalseBB;
16858         }
16859       }
16860     }
16861   }
16862
16863   if (addTest) {
16864     // Look pass the truncate if the high bits are known zero.
16865     if (isTruncWithZeroHighBitsInput(Cond, DAG))
16866         Cond = Cond.getOperand(0);
16867
16868     // We know the result of AND is compared against zero. Try to match
16869     // it to BT.
16870     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16871       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
16872       if (NewSetCC.getNode()) {
16873         CC = NewSetCC.getOperand(0);
16874         Cond = NewSetCC.getOperand(1);
16875         addTest = false;
16876       }
16877     }
16878   }
16879
16880   if (addTest) {
16881     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
16882     CC = DAG.getConstant(X86Cond, MVT::i8);
16883     Cond = EmitTest(Cond, X86Cond, dl, DAG);
16884   }
16885   Cond = ConvertCmpIfNecessary(Cond, DAG);
16886   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16887                      Chain, Dest, CC, Cond);
16888 }
16889
16890 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
16891 // Calls to _alloca are needed to probe the stack when allocating more than 4k
16892 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
16893 // that the guard pages used by the OS virtual memory manager are allocated in
16894 // correct sequence.
16895 SDValue
16896 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
16897                                            SelectionDAG &DAG) const {
16898   MachineFunction &MF = DAG.getMachineFunction();
16899   bool SplitStack = MF.shouldSplitStack();
16900   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
16901                SplitStack;
16902   SDLoc dl(Op);
16903
16904   if (!Lower) {
16905     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16906     SDNode* Node = Op.getNode();
16907
16908     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
16909     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
16910         " not tell us which reg is the stack pointer!");
16911     EVT VT = Node->getValueType(0);
16912     SDValue Tmp1 = SDValue(Node, 0);
16913     SDValue Tmp2 = SDValue(Node, 1);
16914     SDValue Tmp3 = Node->getOperand(2);
16915     SDValue Chain = Tmp1.getOperand(0);
16916
16917     // Chain the dynamic stack allocation so that it doesn't modify the stack
16918     // pointer when other instructions are using the stack.
16919     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
16920         SDLoc(Node));
16921
16922     SDValue Size = Tmp2.getOperand(1);
16923     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
16924     Chain = SP.getValue(1);
16925     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
16926     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16927     unsigned StackAlign = TFI.getStackAlignment();
16928     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
16929     if (Align > StackAlign)
16930       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
16931           DAG.getConstant(-(uint64_t)Align, VT));
16932     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
16933
16934     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
16935         DAG.getIntPtrConstant(0, true), SDValue(),
16936         SDLoc(Node));
16937
16938     SDValue Ops[2] = { Tmp1, Tmp2 };
16939     return DAG.getMergeValues(Ops, dl);
16940   }
16941
16942   // Get the inputs.
16943   SDValue Chain = Op.getOperand(0);
16944   SDValue Size  = Op.getOperand(1);
16945   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16946   EVT VT = Op.getNode()->getValueType(0);
16947
16948   bool Is64Bit = Subtarget->is64Bit();
16949   EVT SPTy = getPointerTy();
16950
16951   if (SplitStack) {
16952     MachineRegisterInfo &MRI = MF.getRegInfo();
16953
16954     if (Is64Bit) {
16955       // The 64 bit implementation of segmented stacks needs to clobber both r10
16956       // r11. This makes it impossible to use it along with nested parameters.
16957       const Function *F = MF.getFunction();
16958
16959       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16960            I != E; ++I)
16961         if (I->hasNestAttr())
16962           report_fatal_error("Cannot use segmented stacks with functions that "
16963                              "have nested arguments.");
16964     }
16965
16966     const TargetRegisterClass *AddrRegClass =
16967       getRegClassFor(getPointerTy());
16968     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16969     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16970     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16971                                 DAG.getRegister(Vreg, SPTy));
16972     SDValue Ops1[2] = { Value, Chain };
16973     return DAG.getMergeValues(Ops1, dl);
16974   } else {
16975     SDValue Flag;
16976     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16977
16978     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16979     Flag = Chain.getValue(1);
16980     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16981
16982     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16983
16984     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16985     unsigned SPReg = RegInfo->getStackRegister();
16986     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16987     Chain = SP.getValue(1);
16988
16989     if (Align) {
16990       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16991                        DAG.getConstant(-(uint64_t)Align, VT));
16992       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16993     }
16994
16995     SDValue Ops1[2] = { SP, Chain };
16996     return DAG.getMergeValues(Ops1, dl);
16997   }
16998 }
16999
17000 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
17001   MachineFunction &MF = DAG.getMachineFunction();
17002   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17003
17004   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
17005   SDLoc DL(Op);
17006
17007   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
17008     // vastart just stores the address of the VarArgsFrameIndex slot into the
17009     // memory location argument.
17010     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
17011                                    getPointerTy());
17012     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
17013                         MachinePointerInfo(SV), false, false, 0);
17014   }
17015
17016   // __va_list_tag:
17017   //   gp_offset         (0 - 6 * 8)
17018   //   fp_offset         (48 - 48 + 8 * 16)
17019   //   overflow_arg_area (point to parameters coming in memory).
17020   //   reg_save_area
17021   SmallVector<SDValue, 8> MemOps;
17022   SDValue FIN = Op.getOperand(1);
17023   // Store gp_offset
17024   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
17025                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
17026                                                MVT::i32),
17027                                FIN, MachinePointerInfo(SV), false, false, 0);
17028   MemOps.push_back(Store);
17029
17030   // Store fp_offset
17031   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
17032                     FIN, DAG.getIntPtrConstant(4));
17033   Store = DAG.getStore(Op.getOperand(0), DL,
17034                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
17035                                        MVT::i32),
17036                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
17037   MemOps.push_back(Store);
17038
17039   // Store ptr to overflow_arg_area
17040   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
17041                     FIN, DAG.getIntPtrConstant(4));
17042   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
17043                                     getPointerTy());
17044   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
17045                        MachinePointerInfo(SV, 8),
17046                        false, false, 0);
17047   MemOps.push_back(Store);
17048
17049   // Store ptr to reg_save_area.
17050   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
17051                     FIN, DAG.getIntPtrConstant(8));
17052   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
17053                                     getPointerTy());
17054   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
17055                        MachinePointerInfo(SV, 16), false, false, 0);
17056   MemOps.push_back(Store);
17057   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
17058 }
17059
17060 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
17061   assert(Subtarget->is64Bit() &&
17062          "LowerVAARG only handles 64-bit va_arg!");
17063   assert((Subtarget->isTargetLinux() ||
17064           Subtarget->isTargetDarwin()) &&
17065           "Unhandled target in LowerVAARG");
17066   assert(Op.getNode()->getNumOperands() == 4);
17067   SDValue Chain = Op.getOperand(0);
17068   SDValue SrcPtr = Op.getOperand(1);
17069   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
17070   unsigned Align = Op.getConstantOperandVal(3);
17071   SDLoc dl(Op);
17072
17073   EVT ArgVT = Op.getNode()->getValueType(0);
17074   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17075   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
17076   uint8_t ArgMode;
17077
17078   // Decide which area this value should be read from.
17079   // TODO: Implement the AMD64 ABI in its entirety. This simple
17080   // selection mechanism works only for the basic types.
17081   if (ArgVT == MVT::f80) {
17082     llvm_unreachable("va_arg for f80 not yet implemented");
17083   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
17084     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
17085   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
17086     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
17087   } else {
17088     llvm_unreachable("Unhandled argument type in LowerVAARG");
17089   }
17090
17091   if (ArgMode == 2) {
17092     // Sanity Check: Make sure using fp_offset makes sense.
17093     assert(!DAG.getTarget().Options.UseSoftFloat &&
17094            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
17095                Attribute::NoImplicitFloat)) &&
17096            Subtarget->hasSSE1());
17097   }
17098
17099   // Insert VAARG_64 node into the DAG
17100   // VAARG_64 returns two values: Variable Argument Address, Chain
17101   SmallVector<SDValue, 11> InstOps;
17102   InstOps.push_back(Chain);
17103   InstOps.push_back(SrcPtr);
17104   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
17105   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
17106   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
17107   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
17108   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
17109                                           VTs, InstOps, MVT::i64,
17110                                           MachinePointerInfo(SV),
17111                                           /*Align=*/0,
17112                                           /*Volatile=*/false,
17113                                           /*ReadMem=*/true,
17114                                           /*WriteMem=*/true);
17115   Chain = VAARG.getValue(1);
17116
17117   // Load the next argument and return it
17118   return DAG.getLoad(ArgVT, dl,
17119                      Chain,
17120                      VAARG,
17121                      MachinePointerInfo(),
17122                      false, false, false, 0);
17123 }
17124
17125 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
17126                            SelectionDAG &DAG) {
17127   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
17128   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
17129   SDValue Chain = Op.getOperand(0);
17130   SDValue DstPtr = Op.getOperand(1);
17131   SDValue SrcPtr = Op.getOperand(2);
17132   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
17133   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17134   SDLoc DL(Op);
17135
17136   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
17137                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
17138                        false,
17139                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
17140 }
17141
17142 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
17143 // amount is a constant. Takes immediate version of shift as input.
17144 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
17145                                           SDValue SrcOp, uint64_t ShiftAmt,
17146                                           SelectionDAG &DAG) {
17147   MVT ElementType = VT.getVectorElementType();
17148
17149   // Fold this packed shift into its first operand if ShiftAmt is 0.
17150   if (ShiftAmt == 0)
17151     return SrcOp;
17152
17153   // Check for ShiftAmt >= element width
17154   if (ShiftAmt >= ElementType.getSizeInBits()) {
17155     if (Opc == X86ISD::VSRAI)
17156       ShiftAmt = ElementType.getSizeInBits() - 1;
17157     else
17158       return DAG.getConstant(0, VT);
17159   }
17160
17161   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
17162          && "Unknown target vector shift-by-constant node");
17163
17164   // Fold this packed vector shift into a build vector if SrcOp is a
17165   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
17166   if (VT == SrcOp.getSimpleValueType() &&
17167       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
17168     SmallVector<SDValue, 8> Elts;
17169     unsigned NumElts = SrcOp->getNumOperands();
17170     ConstantSDNode *ND;
17171
17172     switch(Opc) {
17173     default: llvm_unreachable(nullptr);
17174     case X86ISD::VSHLI:
17175       for (unsigned i=0; i!=NumElts; ++i) {
17176         SDValue CurrentOp = SrcOp->getOperand(i);
17177         if (CurrentOp->getOpcode() == ISD::UNDEF) {
17178           Elts.push_back(CurrentOp);
17179           continue;
17180         }
17181         ND = cast<ConstantSDNode>(CurrentOp);
17182         const APInt &C = ND->getAPIntValue();
17183         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
17184       }
17185       break;
17186     case X86ISD::VSRLI:
17187       for (unsigned i=0; i!=NumElts; ++i) {
17188         SDValue CurrentOp = SrcOp->getOperand(i);
17189         if (CurrentOp->getOpcode() == ISD::UNDEF) {
17190           Elts.push_back(CurrentOp);
17191           continue;
17192         }
17193         ND = cast<ConstantSDNode>(CurrentOp);
17194         const APInt &C = ND->getAPIntValue();
17195         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
17196       }
17197       break;
17198     case X86ISD::VSRAI:
17199       for (unsigned i=0; i!=NumElts; ++i) {
17200         SDValue CurrentOp = SrcOp->getOperand(i);
17201         if (CurrentOp->getOpcode() == ISD::UNDEF) {
17202           Elts.push_back(CurrentOp);
17203           continue;
17204         }
17205         ND = cast<ConstantSDNode>(CurrentOp);
17206         const APInt &C = ND->getAPIntValue();
17207         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
17208       }
17209       break;
17210     }
17211
17212     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17213   }
17214
17215   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
17216 }
17217
17218 // getTargetVShiftNode - Handle vector element shifts where the shift amount
17219 // may or may not be a constant. Takes immediate version of shift as input.
17220 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
17221                                    SDValue SrcOp, SDValue ShAmt,
17222                                    SelectionDAG &DAG) {
17223   MVT SVT = ShAmt.getSimpleValueType();
17224   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
17225
17226   // Catch shift-by-constant.
17227   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
17228     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
17229                                       CShAmt->getZExtValue(), DAG);
17230
17231   // Change opcode to non-immediate version
17232   switch (Opc) {
17233     default: llvm_unreachable("Unknown target vector shift node");
17234     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
17235     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
17236     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
17237   }
17238
17239   const X86Subtarget &Subtarget =
17240       static_cast<const X86Subtarget &>(DAG.getSubtarget());
17241   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
17242       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
17243     // Let the shuffle legalizer expand this shift amount node.
17244     SDValue Op0 = ShAmt.getOperand(0);
17245     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
17246     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
17247   } else {
17248     // Need to build a vector containing shift amount.
17249     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
17250     SmallVector<SDValue, 4> ShOps;
17251     ShOps.push_back(ShAmt);
17252     if (SVT == MVT::i32) {
17253       ShOps.push_back(DAG.getConstant(0, SVT));
17254       ShOps.push_back(DAG.getUNDEF(SVT));
17255     }
17256     ShOps.push_back(DAG.getUNDEF(SVT));
17257
17258     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
17259     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
17260   }
17261
17262   // The return type has to be a 128-bit type with the same element
17263   // type as the input type.
17264   MVT EltVT = VT.getVectorElementType();
17265   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
17266
17267   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
17268   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
17269 }
17270
17271 /// \brief Return (and \p Op, \p Mask) for compare instructions or
17272 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
17273 /// necessary casting for \p Mask when lowering masking intrinsics.
17274 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
17275                                     SDValue PreservedSrc,
17276                                     const X86Subtarget *Subtarget,
17277                                     SelectionDAG &DAG) {
17278     EVT VT = Op.getValueType();
17279     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
17280                                   MVT::i1, VT.getVectorNumElements());
17281     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17282                                      Mask.getValueType().getSizeInBits());
17283     SDLoc dl(Op);
17284
17285     assert(MaskVT.isSimple() && "invalid mask type");
17286
17287     if (isAllOnes(Mask))
17288       return Op;
17289
17290     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17291     // are extracted by EXTRACT_SUBVECTOR.
17292     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17293                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17294                               DAG.getIntPtrConstant(0));
17295
17296     switch (Op.getOpcode()) {
17297       default: break;
17298       case X86ISD::PCMPEQM:
17299       case X86ISD::PCMPGTM:
17300       case X86ISD::CMPM:
17301       case X86ISD::CMPMU:
17302         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
17303     }
17304     if (PreservedSrc.getOpcode() == ISD::UNDEF)
17305       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
17306     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
17307 }
17308
17309 /// \brief Creates an SDNode for a predicated scalar operation.
17310 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
17311 /// The mask is comming as MVT::i8 and it should be truncated
17312 /// to MVT::i1 while lowering masking intrinsics.
17313 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
17314 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
17315 /// a scalar instruction.
17316 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
17317                                     SDValue PreservedSrc,
17318                                     const X86Subtarget *Subtarget,
17319                                     SelectionDAG &DAG) {
17320     if (isAllOnes(Mask))
17321       return Op;
17322
17323     EVT VT = Op.getValueType();
17324     SDLoc dl(Op);
17325     // The mask should be of type MVT::i1
17326     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
17327
17328     if (PreservedSrc.getOpcode() == ISD::UNDEF)
17329       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
17330     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
17331 }
17332
17333 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17334                                        SelectionDAG &DAG) {
17335   SDLoc dl(Op);
17336   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17337   EVT VT = Op.getValueType();
17338   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
17339   if (IntrData) {
17340     switch(IntrData->Type) {
17341     case INTR_TYPE_1OP:
17342       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
17343     case INTR_TYPE_2OP:
17344       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
17345         Op.getOperand(2));
17346     case INTR_TYPE_3OP:
17347       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
17348         Op.getOperand(2), Op.getOperand(3));
17349     case INTR_TYPE_1OP_MASK_RM: {
17350       SDValue Src = Op.getOperand(1);
17351       SDValue Src0 = Op.getOperand(2);
17352       SDValue Mask = Op.getOperand(3);
17353       SDValue RoundingMode = Op.getOperand(4);
17354       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
17355                                               RoundingMode),
17356                                   Mask, Src0, Subtarget, DAG);
17357     }
17358     case INTR_TYPE_SCALAR_MASK_RM: {
17359       SDValue Src1 = Op.getOperand(1);
17360       SDValue Src2 = Op.getOperand(2);
17361       SDValue Src0 = Op.getOperand(3);
17362       SDValue Mask = Op.getOperand(4);
17363       SDValue RoundingMode = Op.getOperand(5);
17364       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
17365                                               RoundingMode),
17366                                   Mask, Src0, Subtarget, DAG);
17367     }
17368     case INTR_TYPE_2OP_MASK: {
17369       SDValue Mask = Op.getOperand(4);
17370       SDValue PassThru = Op.getOperand(3);
17371       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
17372       if (IntrWithRoundingModeOpcode != 0) {
17373         unsigned Round = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
17374         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
17375           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
17376                                       dl, Op.getValueType(),
17377                                       Op.getOperand(1), Op.getOperand(2),
17378                                       Op.getOperand(3), Op.getOperand(5)),
17379                                       Mask, PassThru, Subtarget, DAG);
17380         }
17381       }
17382       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
17383                                               Op.getOperand(1),
17384                                               Op.getOperand(2)),
17385                                   Mask, PassThru, Subtarget, DAG);
17386     }
17387     case FMA_OP_MASK: {
17388       SDValue Src1 = Op.getOperand(1);
17389       SDValue Src2 = Op.getOperand(2);
17390       SDValue Src3 = Op.getOperand(3);
17391       SDValue Mask = Op.getOperand(4);
17392       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
17393       if (IntrWithRoundingModeOpcode != 0) {
17394         SDValue Rnd = Op.getOperand(5);
17395         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
17396             X86::STATIC_ROUNDING::CUR_DIRECTION)
17397           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
17398                                                   dl, Op.getValueType(),
17399                                                   Src1, Src2, Src3, Rnd),
17400                                       Mask, Src1, Subtarget, DAG);
17401       }
17402       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
17403                                               dl, Op.getValueType(),
17404                                               Src1, Src2, Src3),
17405                                   Mask, Src1, Subtarget, DAG);
17406     }
17407     case CMP_MASK:
17408     case CMP_MASK_CC: {
17409       // Comparison intrinsics with masks.
17410       // Example of transformation:
17411       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
17412       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
17413       // (i8 (bitcast
17414       //   (v8i1 (insert_subvector undef,
17415       //           (v2i1 (and (PCMPEQM %a, %b),
17416       //                      (extract_subvector
17417       //                         (v8i1 (bitcast %mask)), 0))), 0))))
17418       EVT VT = Op.getOperand(1).getValueType();
17419       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17420                                     VT.getVectorNumElements());
17421       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
17422       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17423                                        Mask.getValueType().getSizeInBits());
17424       SDValue Cmp;
17425       if (IntrData->Type == CMP_MASK_CC) {
17426         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
17427                     Op.getOperand(2), Op.getOperand(3));
17428       } else {
17429         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
17430         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
17431                     Op.getOperand(2));
17432       }
17433       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
17434                                              DAG.getTargetConstant(0, MaskVT),
17435                                              Subtarget, DAG);
17436       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
17437                                 DAG.getUNDEF(BitcastVT), CmpMask,
17438                                 DAG.getIntPtrConstant(0));
17439       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
17440     }
17441     case COMI: { // Comparison intrinsics
17442       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
17443       SDValue LHS = Op.getOperand(1);
17444       SDValue RHS = Op.getOperand(2);
17445       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
17446       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
17447       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
17448       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17449                                   DAG.getConstant(X86CC, MVT::i8), Cond);
17450       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17451     }
17452     case VSHIFT:
17453       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
17454                                  Op.getOperand(1), Op.getOperand(2), DAG);
17455     case VSHIFT_MASK:
17456       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
17457                                                       Op.getSimpleValueType(),
17458                                                       Op.getOperand(1),
17459                                                       Op.getOperand(2), DAG),
17460                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
17461                                   DAG);
17462     case COMPRESS_EXPAND_IN_REG: {
17463       SDValue Mask = Op.getOperand(3);
17464       SDValue DataToCompress = Op.getOperand(1);
17465       SDValue PassThru = Op.getOperand(2);
17466       if (isAllOnes(Mask)) // return data as is
17467         return Op.getOperand(1);
17468       EVT VT = Op.getValueType();
17469       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17470                                     VT.getVectorNumElements());
17471       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17472                                        Mask.getValueType().getSizeInBits());
17473       SDLoc dl(Op);
17474       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17475                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17476                                   DAG.getIntPtrConstant(0));
17477
17478       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
17479                          PassThru);
17480     }
17481     case BLEND: {
17482       SDValue Mask = Op.getOperand(3);
17483       EVT VT = Op.getValueType();
17484       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17485                                     VT.getVectorNumElements());
17486       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17487                                        Mask.getValueType().getSizeInBits());
17488       SDLoc dl(Op);
17489       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17490                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17491                                   DAG.getIntPtrConstant(0));
17492       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
17493                          Op.getOperand(2));
17494     }
17495     default:
17496       break;
17497     }
17498   }
17499
17500   switch (IntNo) {
17501   default: return SDValue();    // Don't custom lower most intrinsics.
17502
17503   case Intrinsic::x86_avx512_mask_valign_q_512:
17504   case Intrinsic::x86_avx512_mask_valign_d_512:
17505     // Vector source operands are swapped.
17506     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
17507                                             Op.getValueType(), Op.getOperand(2),
17508                                             Op.getOperand(1),
17509                                             Op.getOperand(3)),
17510                                 Op.getOperand(5), Op.getOperand(4),
17511                                 Subtarget, DAG);
17512
17513   // ptest and testp intrinsics. The intrinsic these come from are designed to
17514   // return an integer value, not just an instruction so lower it to the ptest
17515   // or testp pattern and a setcc for the result.
17516   case Intrinsic::x86_sse41_ptestz:
17517   case Intrinsic::x86_sse41_ptestc:
17518   case Intrinsic::x86_sse41_ptestnzc:
17519   case Intrinsic::x86_avx_ptestz_256:
17520   case Intrinsic::x86_avx_ptestc_256:
17521   case Intrinsic::x86_avx_ptestnzc_256:
17522   case Intrinsic::x86_avx_vtestz_ps:
17523   case Intrinsic::x86_avx_vtestc_ps:
17524   case Intrinsic::x86_avx_vtestnzc_ps:
17525   case Intrinsic::x86_avx_vtestz_pd:
17526   case Intrinsic::x86_avx_vtestc_pd:
17527   case Intrinsic::x86_avx_vtestnzc_pd:
17528   case Intrinsic::x86_avx_vtestz_ps_256:
17529   case Intrinsic::x86_avx_vtestc_ps_256:
17530   case Intrinsic::x86_avx_vtestnzc_ps_256:
17531   case Intrinsic::x86_avx_vtestz_pd_256:
17532   case Intrinsic::x86_avx_vtestc_pd_256:
17533   case Intrinsic::x86_avx_vtestnzc_pd_256: {
17534     bool IsTestPacked = false;
17535     unsigned X86CC;
17536     switch (IntNo) {
17537     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17538     case Intrinsic::x86_avx_vtestz_ps:
17539     case Intrinsic::x86_avx_vtestz_pd:
17540     case Intrinsic::x86_avx_vtestz_ps_256:
17541     case Intrinsic::x86_avx_vtestz_pd_256:
17542       IsTestPacked = true; // Fallthrough
17543     case Intrinsic::x86_sse41_ptestz:
17544     case Intrinsic::x86_avx_ptestz_256:
17545       // ZF = 1
17546       X86CC = X86::COND_E;
17547       break;
17548     case Intrinsic::x86_avx_vtestc_ps:
17549     case Intrinsic::x86_avx_vtestc_pd:
17550     case Intrinsic::x86_avx_vtestc_ps_256:
17551     case Intrinsic::x86_avx_vtestc_pd_256:
17552       IsTestPacked = true; // Fallthrough
17553     case Intrinsic::x86_sse41_ptestc:
17554     case Intrinsic::x86_avx_ptestc_256:
17555       // CF = 1
17556       X86CC = X86::COND_B;
17557       break;
17558     case Intrinsic::x86_avx_vtestnzc_ps:
17559     case Intrinsic::x86_avx_vtestnzc_pd:
17560     case Intrinsic::x86_avx_vtestnzc_ps_256:
17561     case Intrinsic::x86_avx_vtestnzc_pd_256:
17562       IsTestPacked = true; // Fallthrough
17563     case Intrinsic::x86_sse41_ptestnzc:
17564     case Intrinsic::x86_avx_ptestnzc_256:
17565       // ZF and CF = 0
17566       X86CC = X86::COND_A;
17567       break;
17568     }
17569
17570     SDValue LHS = Op.getOperand(1);
17571     SDValue RHS = Op.getOperand(2);
17572     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17573     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17574     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17575     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17576     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17577   }
17578   case Intrinsic::x86_avx512_kortestz_w:
17579   case Intrinsic::x86_avx512_kortestc_w: {
17580     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17581     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
17582     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
17583     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17584     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17585     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17586     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17587   }
17588
17589   case Intrinsic::x86_sse42_pcmpistria128:
17590   case Intrinsic::x86_sse42_pcmpestria128:
17591   case Intrinsic::x86_sse42_pcmpistric128:
17592   case Intrinsic::x86_sse42_pcmpestric128:
17593   case Intrinsic::x86_sse42_pcmpistrio128:
17594   case Intrinsic::x86_sse42_pcmpestrio128:
17595   case Intrinsic::x86_sse42_pcmpistris128:
17596   case Intrinsic::x86_sse42_pcmpestris128:
17597   case Intrinsic::x86_sse42_pcmpistriz128:
17598   case Intrinsic::x86_sse42_pcmpestriz128: {
17599     unsigned Opcode;
17600     unsigned X86CC;
17601     switch (IntNo) {
17602     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17603     case Intrinsic::x86_sse42_pcmpistria128:
17604       Opcode = X86ISD::PCMPISTRI;
17605       X86CC = X86::COND_A;
17606       break;
17607     case Intrinsic::x86_sse42_pcmpestria128:
17608       Opcode = X86ISD::PCMPESTRI;
17609       X86CC = X86::COND_A;
17610       break;
17611     case Intrinsic::x86_sse42_pcmpistric128:
17612       Opcode = X86ISD::PCMPISTRI;
17613       X86CC = X86::COND_B;
17614       break;
17615     case Intrinsic::x86_sse42_pcmpestric128:
17616       Opcode = X86ISD::PCMPESTRI;
17617       X86CC = X86::COND_B;
17618       break;
17619     case Intrinsic::x86_sse42_pcmpistrio128:
17620       Opcode = X86ISD::PCMPISTRI;
17621       X86CC = X86::COND_O;
17622       break;
17623     case Intrinsic::x86_sse42_pcmpestrio128:
17624       Opcode = X86ISD::PCMPESTRI;
17625       X86CC = X86::COND_O;
17626       break;
17627     case Intrinsic::x86_sse42_pcmpistris128:
17628       Opcode = X86ISD::PCMPISTRI;
17629       X86CC = X86::COND_S;
17630       break;
17631     case Intrinsic::x86_sse42_pcmpestris128:
17632       Opcode = X86ISD::PCMPESTRI;
17633       X86CC = X86::COND_S;
17634       break;
17635     case Intrinsic::x86_sse42_pcmpistriz128:
17636       Opcode = X86ISD::PCMPISTRI;
17637       X86CC = X86::COND_E;
17638       break;
17639     case Intrinsic::x86_sse42_pcmpestriz128:
17640       Opcode = X86ISD::PCMPESTRI;
17641       X86CC = X86::COND_E;
17642       break;
17643     }
17644     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17645     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17646     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17647     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17648                                 DAG.getConstant(X86CC, MVT::i8),
17649                                 SDValue(PCMP.getNode(), 1));
17650     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17651   }
17652
17653   case Intrinsic::x86_sse42_pcmpistri128:
17654   case Intrinsic::x86_sse42_pcmpestri128: {
17655     unsigned Opcode;
17656     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17657       Opcode = X86ISD::PCMPISTRI;
17658     else
17659       Opcode = X86ISD::PCMPESTRI;
17660
17661     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17662     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17663     return DAG.getNode(Opcode, dl, VTs, NewOps);
17664   }
17665   }
17666 }
17667
17668 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17669                               SDValue Src, SDValue Mask, SDValue Base,
17670                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17671                               const X86Subtarget * Subtarget) {
17672   SDLoc dl(Op);
17673   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17674   assert(C && "Invalid scale type");
17675   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17676   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17677                              Index.getSimpleValueType().getVectorNumElements());
17678   SDValue MaskInReg;
17679   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17680   if (MaskC)
17681     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17682   else
17683     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17684   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17685   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17686   SDValue Segment = DAG.getRegister(0, MVT::i32);
17687   if (Src.getOpcode() == ISD::UNDEF)
17688     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
17689   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17690   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17691   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17692   return DAG.getMergeValues(RetOps, dl);
17693 }
17694
17695 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17696                                SDValue Src, SDValue Mask, SDValue Base,
17697                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17698   SDLoc dl(Op);
17699   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17700   assert(C && "Invalid scale type");
17701   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17702   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17703   SDValue Segment = DAG.getRegister(0, MVT::i32);
17704   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17705                              Index.getSimpleValueType().getVectorNumElements());
17706   SDValue MaskInReg;
17707   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17708   if (MaskC)
17709     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17710   else
17711     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17712   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17713   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17714   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17715   return SDValue(Res, 1);
17716 }
17717
17718 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17719                                SDValue Mask, SDValue Base, SDValue Index,
17720                                SDValue ScaleOp, SDValue Chain) {
17721   SDLoc dl(Op);
17722   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17723   assert(C && "Invalid scale type");
17724   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17725   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17726   SDValue Segment = DAG.getRegister(0, MVT::i32);
17727   EVT MaskVT =
17728     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17729   SDValue MaskInReg;
17730   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17731   if (MaskC)
17732     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17733   else
17734     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17735   //SDVTList VTs = DAG.getVTList(MVT::Other);
17736   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17737   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17738   return SDValue(Res, 0);
17739 }
17740
17741 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17742 // read performance monitor counters (x86_rdpmc).
17743 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17744                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17745                               SmallVectorImpl<SDValue> &Results) {
17746   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17747   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17748   SDValue LO, HI;
17749
17750   // The ECX register is used to select the index of the performance counter
17751   // to read.
17752   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17753                                    N->getOperand(2));
17754   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17755
17756   // Reads the content of a 64-bit performance counter and returns it in the
17757   // registers EDX:EAX.
17758   if (Subtarget->is64Bit()) {
17759     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17760     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17761                             LO.getValue(2));
17762   } else {
17763     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17764     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17765                             LO.getValue(2));
17766   }
17767   Chain = HI.getValue(1);
17768
17769   if (Subtarget->is64Bit()) {
17770     // The EAX register is loaded with the low-order 32 bits. The EDX register
17771     // is loaded with the supported high-order bits of the counter.
17772     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17773                               DAG.getConstant(32, MVT::i8));
17774     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17775     Results.push_back(Chain);
17776     return;
17777   }
17778
17779   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17780   SDValue Ops[] = { LO, HI };
17781   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17782   Results.push_back(Pair);
17783   Results.push_back(Chain);
17784 }
17785
17786 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17787 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17788 // also used to custom lower READCYCLECOUNTER nodes.
17789 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17790                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17791                               SmallVectorImpl<SDValue> &Results) {
17792   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17793   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17794   SDValue LO, HI;
17795
17796   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17797   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17798   // and the EAX register is loaded with the low-order 32 bits.
17799   if (Subtarget->is64Bit()) {
17800     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17801     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17802                             LO.getValue(2));
17803   } else {
17804     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17805     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17806                             LO.getValue(2));
17807   }
17808   SDValue Chain = HI.getValue(1);
17809
17810   if (Opcode == X86ISD::RDTSCP_DAG) {
17811     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17812
17813     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17814     // the ECX register. Add 'ecx' explicitly to the chain.
17815     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17816                                      HI.getValue(2));
17817     // Explicitly store the content of ECX at the location passed in input
17818     // to the 'rdtscp' intrinsic.
17819     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17820                          MachinePointerInfo(), false, false, 0);
17821   }
17822
17823   if (Subtarget->is64Bit()) {
17824     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17825     // the EAX register is loaded with the low-order 32 bits.
17826     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17827                               DAG.getConstant(32, MVT::i8));
17828     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17829     Results.push_back(Chain);
17830     return;
17831   }
17832
17833   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17834   SDValue Ops[] = { LO, HI };
17835   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17836   Results.push_back(Pair);
17837   Results.push_back(Chain);
17838 }
17839
17840 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17841                                      SelectionDAG &DAG) {
17842   SmallVector<SDValue, 2> Results;
17843   SDLoc DL(Op);
17844   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17845                           Results);
17846   return DAG.getMergeValues(Results, DL);
17847 }
17848
17849
17850 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17851                                       SelectionDAG &DAG) {
17852   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17853
17854   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17855   if (!IntrData)
17856     return SDValue();
17857
17858   SDLoc dl(Op);
17859   switch(IntrData->Type) {
17860   default:
17861     llvm_unreachable("Unknown Intrinsic Type");
17862     break;
17863   case RDSEED:
17864   case RDRAND: {
17865     // Emit the node with the right value type.
17866     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17867     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17868
17869     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17870     // Otherwise return the value from Rand, which is always 0, casted to i32.
17871     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17872                       DAG.getConstant(1, Op->getValueType(1)),
17873                       DAG.getConstant(X86::COND_B, MVT::i32),
17874                       SDValue(Result.getNode(), 1) };
17875     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17876                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17877                                   Ops);
17878
17879     // Return { result, isValid, chain }.
17880     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17881                        SDValue(Result.getNode(), 2));
17882   }
17883   case GATHER: {
17884   //gather(v1, mask, index, base, scale);
17885     SDValue Chain = Op.getOperand(0);
17886     SDValue Src   = Op.getOperand(2);
17887     SDValue Base  = Op.getOperand(3);
17888     SDValue Index = Op.getOperand(4);
17889     SDValue Mask  = Op.getOperand(5);
17890     SDValue Scale = Op.getOperand(6);
17891     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
17892                           Subtarget);
17893   }
17894   case SCATTER: {
17895   //scatter(base, mask, index, v1, scale);
17896     SDValue Chain = Op.getOperand(0);
17897     SDValue Base  = Op.getOperand(2);
17898     SDValue Mask  = Op.getOperand(3);
17899     SDValue Index = Op.getOperand(4);
17900     SDValue Src   = Op.getOperand(5);
17901     SDValue Scale = Op.getOperand(6);
17902     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
17903   }
17904   case PREFETCH: {
17905     SDValue Hint = Op.getOperand(6);
17906     unsigned HintVal;
17907     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
17908         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
17909       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
17910     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17911     SDValue Chain = Op.getOperand(0);
17912     SDValue Mask  = Op.getOperand(2);
17913     SDValue Index = Op.getOperand(3);
17914     SDValue Base  = Op.getOperand(4);
17915     SDValue Scale = Op.getOperand(5);
17916     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17917   }
17918   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17919   case RDTSC: {
17920     SmallVector<SDValue, 2> Results;
17921     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
17922     return DAG.getMergeValues(Results, dl);
17923   }
17924   // Read Performance Monitoring Counters.
17925   case RDPMC: {
17926     SmallVector<SDValue, 2> Results;
17927     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17928     return DAG.getMergeValues(Results, dl);
17929   }
17930   // XTEST intrinsics.
17931   case XTEST: {
17932     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17933     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17934     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17935                                 DAG.getConstant(X86::COND_NE, MVT::i8),
17936                                 InTrans);
17937     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17938     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17939                        Ret, SDValue(InTrans.getNode(), 1));
17940   }
17941   // ADC/ADCX/SBB
17942   case ADX: {
17943     SmallVector<SDValue, 2> Results;
17944     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17945     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17946     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17947                                 DAG.getConstant(-1, MVT::i8));
17948     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17949                               Op.getOperand(4), GenCF.getValue(1));
17950     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17951                                  Op.getOperand(5), MachinePointerInfo(),
17952                                  false, false, 0);
17953     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17954                                 DAG.getConstant(X86::COND_B, MVT::i8),
17955                                 Res.getValue(1));
17956     Results.push_back(SetCC);
17957     Results.push_back(Store);
17958     return DAG.getMergeValues(Results, dl);
17959   }
17960   case COMPRESS_TO_MEM: {
17961     SDLoc dl(Op);
17962     SDValue Mask = Op.getOperand(4);
17963     SDValue DataToCompress = Op.getOperand(3);
17964     SDValue Addr = Op.getOperand(2);
17965     SDValue Chain = Op.getOperand(0);
17966
17967     if (isAllOnes(Mask)) // return just a store
17968       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17969                           MachinePointerInfo(), false, false, 0);
17970
17971     EVT VT = DataToCompress.getValueType();
17972     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17973                                   VT.getVectorNumElements());
17974     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17975                                      Mask.getValueType().getSizeInBits());
17976     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17977                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17978                                 DAG.getIntPtrConstant(0));
17979
17980     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
17981                                       DataToCompress, DAG.getUNDEF(VT));
17982     return DAG.getStore(Chain, dl, Compressed, Addr,
17983                         MachinePointerInfo(), false, false, 0);
17984   }
17985   case EXPAND_FROM_MEM: {
17986     SDLoc dl(Op);
17987     SDValue Mask = Op.getOperand(4);
17988     SDValue PathThru = Op.getOperand(3);
17989     SDValue Addr = Op.getOperand(2);
17990     SDValue Chain = Op.getOperand(0);
17991     EVT VT = Op.getValueType();
17992
17993     if (isAllOnes(Mask)) // return just a load
17994       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17995                          false, 0);
17996     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17997                                   VT.getVectorNumElements());
17998     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17999                                      Mask.getValueType().getSizeInBits());
18000     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
18001                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
18002                                 DAG.getIntPtrConstant(0));
18003
18004     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
18005                                    false, false, false, 0);
18006
18007     SmallVector<SDValue, 2> Results;
18008     Results.push_back(DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand,
18009                                   PathThru));
18010     Results.push_back(Chain);
18011     return DAG.getMergeValues(Results, dl);
18012   }
18013   }
18014 }
18015
18016 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
18017                                            SelectionDAG &DAG) const {
18018   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
18019   MFI->setReturnAddressIsTaken(true);
18020
18021   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
18022     return SDValue();
18023
18024   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18025   SDLoc dl(Op);
18026   EVT PtrVT = getPointerTy();
18027
18028   if (Depth > 0) {
18029     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
18030     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18031     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
18032     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
18033                        DAG.getNode(ISD::ADD, dl, PtrVT,
18034                                    FrameAddr, Offset),
18035                        MachinePointerInfo(), false, false, false, 0);
18036   }
18037
18038   // Just load the return address.
18039   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
18040   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
18041                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
18042 }
18043
18044 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
18045   MachineFunction &MF = DAG.getMachineFunction();
18046   MachineFrameInfo *MFI = MF.getFrameInfo();
18047   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
18048   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18049   EVT VT = Op.getValueType();
18050
18051   MFI->setFrameAddressIsTaken(true);
18052
18053   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
18054     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
18055     // is not possible to crawl up the stack without looking at the unwind codes
18056     // simultaneously.
18057     int FrameAddrIndex = FuncInfo->getFAIndex();
18058     if (!FrameAddrIndex) {
18059       // Set up a frame object for the return address.
18060       unsigned SlotSize = RegInfo->getSlotSize();
18061       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
18062           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
18063       FuncInfo->setFAIndex(FrameAddrIndex);
18064     }
18065     return DAG.getFrameIndex(FrameAddrIndex, VT);
18066   }
18067
18068   unsigned FrameReg =
18069       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
18070   SDLoc dl(Op);  // FIXME probably not meaningful
18071   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18072   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
18073           (FrameReg == X86::EBP && VT == MVT::i32)) &&
18074          "Invalid Frame Register!");
18075   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
18076   while (Depth--)
18077     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
18078                             MachinePointerInfo(),
18079                             false, false, false, 0);
18080   return FrameAddr;
18081 }
18082
18083 // FIXME? Maybe this could be a TableGen attribute on some registers and
18084 // this table could be generated automatically from RegInfo.
18085 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
18086                                               EVT VT) const {
18087   unsigned Reg = StringSwitch<unsigned>(RegName)
18088                        .Case("esp", X86::ESP)
18089                        .Case("rsp", X86::RSP)
18090                        .Default(0);
18091   if (Reg)
18092     return Reg;
18093   report_fatal_error("Invalid register name global variable");
18094 }
18095
18096 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
18097                                                      SelectionDAG &DAG) const {
18098   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18099   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
18100 }
18101
18102 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
18103   SDValue Chain     = Op.getOperand(0);
18104   SDValue Offset    = Op.getOperand(1);
18105   SDValue Handler   = Op.getOperand(2);
18106   SDLoc dl      (Op);
18107
18108   EVT PtrVT = getPointerTy();
18109   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18110   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
18111   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
18112           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
18113          "Invalid Frame Register!");
18114   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
18115   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
18116
18117   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
18118                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
18119   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
18120   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
18121                        false, false, 0);
18122   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
18123
18124   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
18125                      DAG.getRegister(StoreAddrReg, PtrVT));
18126 }
18127
18128 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
18129                                                SelectionDAG &DAG) const {
18130   SDLoc DL(Op);
18131   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
18132                      DAG.getVTList(MVT::i32, MVT::Other),
18133                      Op.getOperand(0), Op.getOperand(1));
18134 }
18135
18136 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
18137                                                 SelectionDAG &DAG) const {
18138   SDLoc DL(Op);
18139   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
18140                      Op.getOperand(0), Op.getOperand(1));
18141 }
18142
18143 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
18144   return Op.getOperand(0);
18145 }
18146
18147 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
18148                                                 SelectionDAG &DAG) const {
18149   SDValue Root = Op.getOperand(0);
18150   SDValue Trmp = Op.getOperand(1); // trampoline
18151   SDValue FPtr = Op.getOperand(2); // nested function
18152   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
18153   SDLoc dl (Op);
18154
18155   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
18156   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18157
18158   if (Subtarget->is64Bit()) {
18159     SDValue OutChains[6];
18160
18161     // Large code-model.
18162     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
18163     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
18164
18165     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
18166     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
18167
18168     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
18169
18170     // Load the pointer to the nested function into R11.
18171     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
18172     SDValue Addr = Trmp;
18173     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
18174                                 Addr, MachinePointerInfo(TrmpAddr),
18175                                 false, false, 0);
18176
18177     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
18178                        DAG.getConstant(2, MVT::i64));
18179     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
18180                                 MachinePointerInfo(TrmpAddr, 2),
18181                                 false, false, 2);
18182
18183     // Load the 'nest' parameter value into R10.
18184     // R10 is specified in X86CallingConv.td
18185     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
18186     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
18187                        DAG.getConstant(10, MVT::i64));
18188     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
18189                                 Addr, MachinePointerInfo(TrmpAddr, 10),
18190                                 false, false, 0);
18191
18192     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
18193                        DAG.getConstant(12, MVT::i64));
18194     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
18195                                 MachinePointerInfo(TrmpAddr, 12),
18196                                 false, false, 2);
18197
18198     // Jump to the nested function.
18199     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
18200     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
18201                        DAG.getConstant(20, MVT::i64));
18202     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
18203                                 Addr, MachinePointerInfo(TrmpAddr, 20),
18204                                 false, false, 0);
18205
18206     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
18207     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
18208                        DAG.getConstant(22, MVT::i64));
18209     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
18210                                 MachinePointerInfo(TrmpAddr, 22),
18211                                 false, false, 0);
18212
18213     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
18214   } else {
18215     const Function *Func =
18216       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
18217     CallingConv::ID CC = Func->getCallingConv();
18218     unsigned NestReg;
18219
18220     switch (CC) {
18221     default:
18222       llvm_unreachable("Unsupported calling convention");
18223     case CallingConv::C:
18224     case CallingConv::X86_StdCall: {
18225       // Pass 'nest' parameter in ECX.
18226       // Must be kept in sync with X86CallingConv.td
18227       NestReg = X86::ECX;
18228
18229       // Check that ECX wasn't needed by an 'inreg' parameter.
18230       FunctionType *FTy = Func->getFunctionType();
18231       const AttributeSet &Attrs = Func->getAttributes();
18232
18233       if (!Attrs.isEmpty() && !Func->isVarArg()) {
18234         unsigned InRegCount = 0;
18235         unsigned Idx = 1;
18236
18237         for (FunctionType::param_iterator I = FTy->param_begin(),
18238              E = FTy->param_end(); I != E; ++I, ++Idx)
18239           if (Attrs.hasAttribute(Idx, Attribute::InReg))
18240             // FIXME: should only count parameters that are lowered to integers.
18241             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
18242
18243         if (InRegCount > 2) {
18244           report_fatal_error("Nest register in use - reduce number of inreg"
18245                              " parameters!");
18246         }
18247       }
18248       break;
18249     }
18250     case CallingConv::X86_FastCall:
18251     case CallingConv::X86_ThisCall:
18252     case CallingConv::Fast:
18253       // Pass 'nest' parameter in EAX.
18254       // Must be kept in sync with X86CallingConv.td
18255       NestReg = X86::EAX;
18256       break;
18257     }
18258
18259     SDValue OutChains[4];
18260     SDValue Addr, Disp;
18261
18262     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
18263                        DAG.getConstant(10, MVT::i32));
18264     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
18265
18266     // This is storing the opcode for MOV32ri.
18267     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
18268     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
18269     OutChains[0] = DAG.getStore(Root, dl,
18270                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
18271                                 Trmp, MachinePointerInfo(TrmpAddr),
18272                                 false, false, 0);
18273
18274     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
18275                        DAG.getConstant(1, MVT::i32));
18276     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
18277                                 MachinePointerInfo(TrmpAddr, 1),
18278                                 false, false, 1);
18279
18280     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
18281     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
18282                        DAG.getConstant(5, MVT::i32));
18283     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
18284                                 MachinePointerInfo(TrmpAddr, 5),
18285                                 false, false, 1);
18286
18287     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
18288                        DAG.getConstant(6, MVT::i32));
18289     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
18290                                 MachinePointerInfo(TrmpAddr, 6),
18291                                 false, false, 1);
18292
18293     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
18294   }
18295 }
18296
18297 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
18298                                             SelectionDAG &DAG) const {
18299   /*
18300    The rounding mode is in bits 11:10 of FPSR, and has the following
18301    settings:
18302      00 Round to nearest
18303      01 Round to -inf
18304      10 Round to +inf
18305      11 Round to 0
18306
18307   FLT_ROUNDS, on the other hand, expects the following:
18308     -1 Undefined
18309      0 Round to 0
18310      1 Round to nearest
18311      2 Round to +inf
18312      3 Round to -inf
18313
18314   To perform the conversion, we do:
18315     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
18316   */
18317
18318   MachineFunction &MF = DAG.getMachineFunction();
18319   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
18320   unsigned StackAlignment = TFI.getStackAlignment();
18321   MVT VT = Op.getSimpleValueType();
18322   SDLoc DL(Op);
18323
18324   // Save FP Control Word to stack slot
18325   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
18326   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
18327
18328   MachineMemOperand *MMO =
18329    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
18330                            MachineMemOperand::MOStore, 2, 2);
18331
18332   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
18333   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
18334                                           DAG.getVTList(MVT::Other),
18335                                           Ops, MVT::i16, MMO);
18336
18337   // Load FP Control Word from stack slot
18338   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
18339                             MachinePointerInfo(), false, false, false, 0);
18340
18341   // Transform as necessary
18342   SDValue CWD1 =
18343     DAG.getNode(ISD::SRL, DL, MVT::i16,
18344                 DAG.getNode(ISD::AND, DL, MVT::i16,
18345                             CWD, DAG.getConstant(0x800, MVT::i16)),
18346                 DAG.getConstant(11, MVT::i8));
18347   SDValue CWD2 =
18348     DAG.getNode(ISD::SRL, DL, MVT::i16,
18349                 DAG.getNode(ISD::AND, DL, MVT::i16,
18350                             CWD, DAG.getConstant(0x400, MVT::i16)),
18351                 DAG.getConstant(9, MVT::i8));
18352
18353   SDValue RetVal =
18354     DAG.getNode(ISD::AND, DL, MVT::i16,
18355                 DAG.getNode(ISD::ADD, DL, MVT::i16,
18356                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
18357                             DAG.getConstant(1, MVT::i16)),
18358                 DAG.getConstant(3, MVT::i16));
18359
18360   return DAG.getNode((VT.getSizeInBits() < 16 ?
18361                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
18362 }
18363
18364 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
18365   MVT VT = Op.getSimpleValueType();
18366   EVT OpVT = VT;
18367   unsigned NumBits = VT.getSizeInBits();
18368   SDLoc dl(Op);
18369
18370   Op = Op.getOperand(0);
18371   if (VT == MVT::i8) {
18372     // Zero extend to i32 since there is not an i8 bsr.
18373     OpVT = MVT::i32;
18374     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18375   }
18376
18377   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18378   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18379   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18380
18381   // If src is zero (i.e. bsr sets ZF), returns NumBits.
18382   SDValue Ops[] = {
18383     Op,
18384     DAG.getConstant(NumBits+NumBits-1, OpVT),
18385     DAG.getConstant(X86::COND_E, MVT::i8),
18386     Op.getValue(1)
18387   };
18388   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18389
18390   // Finally xor with NumBits-1.
18391   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
18392
18393   if (VT == MVT::i8)
18394     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18395   return Op;
18396 }
18397
18398 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
18399   MVT VT = Op.getSimpleValueType();
18400   EVT OpVT = VT;
18401   unsigned NumBits = VT.getSizeInBits();
18402   SDLoc dl(Op);
18403
18404   Op = Op.getOperand(0);
18405   if (VT == MVT::i8) {
18406     // Zero extend to i32 since there is not an i8 bsr.
18407     OpVT = MVT::i32;
18408     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18409   }
18410
18411   // Issue a bsr (scan bits in reverse).
18412   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18413   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18414
18415   // And xor with NumBits-1.
18416   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
18417
18418   if (VT == MVT::i8)
18419     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18420   return Op;
18421 }
18422
18423 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18424   MVT VT = Op.getSimpleValueType();
18425   unsigned NumBits = VT.getSizeInBits();
18426   SDLoc dl(Op);
18427   Op = Op.getOperand(0);
18428
18429   // Issue a bsf (scan bits forward) which also sets EFLAGS.
18430   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18431   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
18432
18433   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18434   SDValue Ops[] = {
18435     Op,
18436     DAG.getConstant(NumBits, VT),
18437     DAG.getConstant(X86::COND_E, MVT::i8),
18438     Op.getValue(1)
18439   };
18440   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18441 }
18442
18443 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18444 // ones, and then concatenate the result back.
18445 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18446   MVT VT = Op.getSimpleValueType();
18447
18448   assert(VT.is256BitVector() && VT.isInteger() &&
18449          "Unsupported value type for operation");
18450
18451   unsigned NumElems = VT.getVectorNumElements();
18452   SDLoc dl(Op);
18453
18454   // Extract the LHS vectors
18455   SDValue LHS = Op.getOperand(0);
18456   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18457   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18458
18459   // Extract the RHS vectors
18460   SDValue RHS = Op.getOperand(1);
18461   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18462   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18463
18464   MVT EltVT = VT.getVectorElementType();
18465   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18466
18467   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18468                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18469                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18470 }
18471
18472 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18473   assert(Op.getSimpleValueType().is256BitVector() &&
18474          Op.getSimpleValueType().isInteger() &&
18475          "Only handle AVX 256-bit vector integer operation");
18476   return Lower256IntArith(Op, DAG);
18477 }
18478
18479 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18480   assert(Op.getSimpleValueType().is256BitVector() &&
18481          Op.getSimpleValueType().isInteger() &&
18482          "Only handle AVX 256-bit vector integer operation");
18483   return Lower256IntArith(Op, DAG);
18484 }
18485
18486 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18487                         SelectionDAG &DAG) {
18488   SDLoc dl(Op);
18489   MVT VT = Op.getSimpleValueType();
18490
18491   // Decompose 256-bit ops into smaller 128-bit ops.
18492   if (VT.is256BitVector() && !Subtarget->hasInt256())
18493     return Lower256IntArith(Op, DAG);
18494
18495   SDValue A = Op.getOperand(0);
18496   SDValue B = Op.getOperand(1);
18497
18498   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18499   if (VT == MVT::v4i32) {
18500     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18501            "Should not custom lower when pmuldq is available!");
18502
18503     // Extract the odd parts.
18504     static const int UnpackMask[] = { 1, -1, 3, -1 };
18505     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18506     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18507
18508     // Multiply the even parts.
18509     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18510     // Now multiply odd parts.
18511     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18512
18513     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
18514     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
18515
18516     // Merge the two vectors back together with a shuffle. This expands into 2
18517     // shuffles.
18518     static const int ShufMask[] = { 0, 4, 2, 6 };
18519     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18520   }
18521
18522   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18523          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18524
18525   //  Ahi = psrlqi(a, 32);
18526   //  Bhi = psrlqi(b, 32);
18527   //
18528   //  AloBlo = pmuludq(a, b);
18529   //  AloBhi = pmuludq(a, Bhi);
18530   //  AhiBlo = pmuludq(Ahi, b);
18531
18532   //  AloBhi = psllqi(AloBhi, 32);
18533   //  AhiBlo = psllqi(AhiBlo, 32);
18534   //  return AloBlo + AloBhi + AhiBlo;
18535
18536   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18537   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18538
18539   // Bit cast to 32-bit vectors for MULUDQ
18540   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18541                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18542   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
18543   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
18544   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
18545   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
18546
18547   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18548   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18549   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18550
18551   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18552   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18553
18554   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18555   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18556 }
18557
18558 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18559   assert(Subtarget->isTargetWin64() && "Unexpected target");
18560   EVT VT = Op.getValueType();
18561   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18562          "Unexpected return type for lowering");
18563
18564   RTLIB::Libcall LC;
18565   bool isSigned;
18566   switch (Op->getOpcode()) {
18567   default: llvm_unreachable("Unexpected request for libcall!");
18568   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18569   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18570   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18571   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18572   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18573   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18574   }
18575
18576   SDLoc dl(Op);
18577   SDValue InChain = DAG.getEntryNode();
18578
18579   TargetLowering::ArgListTy Args;
18580   TargetLowering::ArgListEntry Entry;
18581   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18582     EVT ArgVT = Op->getOperand(i).getValueType();
18583     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18584            "Unexpected argument type for lowering");
18585     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18586     Entry.Node = StackPtr;
18587     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18588                            false, false, 16);
18589     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18590     Entry.Ty = PointerType::get(ArgTy,0);
18591     Entry.isSExt = false;
18592     Entry.isZExt = false;
18593     Args.push_back(Entry);
18594   }
18595
18596   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18597                                          getPointerTy());
18598
18599   TargetLowering::CallLoweringInfo CLI(DAG);
18600   CLI.setDebugLoc(dl).setChain(InChain)
18601     .setCallee(getLibcallCallingConv(LC),
18602                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18603                Callee, std::move(Args), 0)
18604     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18605
18606   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18607   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
18608 }
18609
18610 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18611                              SelectionDAG &DAG) {
18612   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18613   EVT VT = Op0.getValueType();
18614   SDLoc dl(Op);
18615
18616   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18617          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18618
18619   // PMULxD operations multiply each even value (starting at 0) of LHS with
18620   // the related value of RHS and produce a widen result.
18621   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18622   // => <2 x i64> <ae|cg>
18623   //
18624   // In other word, to have all the results, we need to perform two PMULxD:
18625   // 1. one with the even values.
18626   // 2. one with the odd values.
18627   // To achieve #2, with need to place the odd values at an even position.
18628   //
18629   // Place the odd value at an even position (basically, shift all values 1
18630   // step to the left):
18631   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18632   // <a|b|c|d> => <b|undef|d|undef>
18633   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18634   // <e|f|g|h> => <f|undef|h|undef>
18635   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18636
18637   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18638   // ints.
18639   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18640   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18641   unsigned Opcode =
18642       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18643   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18644   // => <2 x i64> <ae|cg>
18645   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
18646                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18647   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18648   // => <2 x i64> <bf|dh>
18649   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
18650                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18651
18652   // Shuffle it back into the right order.
18653   SDValue Highs, Lows;
18654   if (VT == MVT::v8i32) {
18655     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18656     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18657     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18658     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18659   } else {
18660     const int HighMask[] = {1, 5, 3, 7};
18661     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18662     const int LowMask[] = {0, 4, 2, 6};
18663     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18664   }
18665
18666   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18667   // unsigned multiply.
18668   if (IsSigned && !Subtarget->hasSSE41()) {
18669     SDValue ShAmt =
18670         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
18671     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18672                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18673     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18674                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18675
18676     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18677     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18678   }
18679
18680   // The first result of MUL_LOHI is actually the low value, followed by the
18681   // high value.
18682   SDValue Ops[] = {Lows, Highs};
18683   return DAG.getMergeValues(Ops, dl);
18684 }
18685
18686 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18687                                          const X86Subtarget *Subtarget) {
18688   MVT VT = Op.getSimpleValueType();
18689   SDLoc dl(Op);
18690   SDValue R = Op.getOperand(0);
18691   SDValue Amt = Op.getOperand(1);
18692
18693   // Optimize shl/srl/sra with constant shift amount.
18694   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18695     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18696       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18697
18698       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
18699           (Subtarget->hasInt256() &&
18700            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18701           (Subtarget->hasAVX512() &&
18702            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18703         if (Op.getOpcode() == ISD::SHL)
18704           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18705                                             DAG);
18706         if (Op.getOpcode() == ISD::SRL)
18707           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18708                                             DAG);
18709         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
18710           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18711                                             DAG);
18712       }
18713
18714       if (VT == MVT::v16i8) {
18715         if (Op.getOpcode() == ISD::SHL) {
18716           // Make a large shift.
18717           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18718                                                    MVT::v8i16, R, ShiftAmt,
18719                                                    DAG);
18720           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18721           // Zero out the rightmost bits.
18722           SmallVector<SDValue, 16> V(16,
18723                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18724                                                      MVT::i8));
18725           return DAG.getNode(ISD::AND, dl, VT, SHL,
18726                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18727         }
18728         if (Op.getOpcode() == ISD::SRL) {
18729           // Make a large shift.
18730           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18731                                                    MVT::v8i16, R, ShiftAmt,
18732                                                    DAG);
18733           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18734           // Zero out the leftmost bits.
18735           SmallVector<SDValue, 16> V(16,
18736                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18737                                                      MVT::i8));
18738           return DAG.getNode(ISD::AND, dl, VT, SRL,
18739                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18740         }
18741         if (Op.getOpcode() == ISD::SRA) {
18742           if (ShiftAmt == 7) {
18743             // R s>> 7  ===  R s< 0
18744             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18745             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18746           }
18747
18748           // R s>> a === ((R u>> a) ^ m) - m
18749           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18750           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
18751                                                          MVT::i8));
18752           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18753           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18754           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18755           return Res;
18756         }
18757         llvm_unreachable("Unknown shift opcode.");
18758       }
18759
18760       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
18761         if (Op.getOpcode() == ISD::SHL) {
18762           // Make a large shift.
18763           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18764                                                    MVT::v16i16, R, ShiftAmt,
18765                                                    DAG);
18766           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18767           // Zero out the rightmost bits.
18768           SmallVector<SDValue, 32> V(32,
18769                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18770                                                      MVT::i8));
18771           return DAG.getNode(ISD::AND, dl, VT, SHL,
18772                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18773         }
18774         if (Op.getOpcode() == ISD::SRL) {
18775           // Make a large shift.
18776           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18777                                                    MVT::v16i16, R, ShiftAmt,
18778                                                    DAG);
18779           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18780           // Zero out the leftmost bits.
18781           SmallVector<SDValue, 32> V(32,
18782                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18783                                                      MVT::i8));
18784           return DAG.getNode(ISD::AND, dl, VT, SRL,
18785                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18786         }
18787         if (Op.getOpcode() == ISD::SRA) {
18788           if (ShiftAmt == 7) {
18789             // R s>> 7  ===  R s< 0
18790             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18791             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18792           }
18793
18794           // R s>> a === ((R u>> a) ^ m) - m
18795           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18796           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
18797                                                          MVT::i8));
18798           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18799           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18800           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18801           return Res;
18802         }
18803         llvm_unreachable("Unknown shift opcode.");
18804       }
18805     }
18806   }
18807
18808   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18809   if (!Subtarget->is64Bit() &&
18810       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18811       Amt.getOpcode() == ISD::BITCAST &&
18812       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18813     Amt = Amt.getOperand(0);
18814     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18815                      VT.getVectorNumElements();
18816     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18817     uint64_t ShiftAmt = 0;
18818     for (unsigned i = 0; i != Ratio; ++i) {
18819       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
18820       if (!C)
18821         return SDValue();
18822       // 6 == Log2(64)
18823       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18824     }
18825     // Check remaining shift amounts.
18826     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18827       uint64_t ShAmt = 0;
18828       for (unsigned j = 0; j != Ratio; ++j) {
18829         ConstantSDNode *C =
18830           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18831         if (!C)
18832           return SDValue();
18833         // 6 == Log2(64)
18834         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18835       }
18836       if (ShAmt != ShiftAmt)
18837         return SDValue();
18838     }
18839     switch (Op.getOpcode()) {
18840     default:
18841       llvm_unreachable("Unknown shift opcode!");
18842     case ISD::SHL:
18843       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18844                                         DAG);
18845     case ISD::SRL:
18846       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18847                                         DAG);
18848     case ISD::SRA:
18849       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18850                                         DAG);
18851     }
18852   }
18853
18854   return SDValue();
18855 }
18856
18857 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18858                                         const X86Subtarget* Subtarget) {
18859   MVT VT = Op.getSimpleValueType();
18860   SDLoc dl(Op);
18861   SDValue R = Op.getOperand(0);
18862   SDValue Amt = Op.getOperand(1);
18863
18864   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
18865       VT == MVT::v4i32 || VT == MVT::v8i16 ||
18866       (Subtarget->hasInt256() &&
18867        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
18868         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18869        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18870     SDValue BaseShAmt;
18871     EVT EltVT = VT.getVectorElementType();
18872
18873     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18874       // Check if this build_vector node is doing a splat.
18875       // If so, then set BaseShAmt equal to the splat value.
18876       BaseShAmt = BV->getSplatValue();
18877       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18878         BaseShAmt = SDValue();
18879     } else {
18880       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18881         Amt = Amt.getOperand(0);
18882
18883       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18884       if (SVN && SVN->isSplat()) {
18885         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18886         SDValue InVec = Amt.getOperand(0);
18887         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18888           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18889                  "Unexpected shuffle index found!");
18890           BaseShAmt = InVec.getOperand(SplatIdx);
18891         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18892            if (ConstantSDNode *C =
18893                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18894              if (C->getZExtValue() == SplatIdx)
18895                BaseShAmt = InVec.getOperand(1);
18896            }
18897         }
18898
18899         if (!BaseShAmt)
18900           // Avoid introducing an extract element from a shuffle.
18901           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18902                                     DAG.getIntPtrConstant(SplatIdx));
18903       }
18904     }
18905
18906     if (BaseShAmt.getNode()) {
18907       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18908       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18909         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18910       else if (EltVT.bitsLT(MVT::i32))
18911         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18912
18913       switch (Op.getOpcode()) {
18914       default:
18915         llvm_unreachable("Unknown shift opcode!");
18916       case ISD::SHL:
18917         switch (VT.SimpleTy) {
18918         default: return SDValue();
18919         case MVT::v2i64:
18920         case MVT::v4i32:
18921         case MVT::v8i16:
18922         case MVT::v4i64:
18923         case MVT::v8i32:
18924         case MVT::v16i16:
18925         case MVT::v16i32:
18926         case MVT::v8i64:
18927           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
18928         }
18929       case ISD::SRA:
18930         switch (VT.SimpleTy) {
18931         default: return SDValue();
18932         case MVT::v4i32:
18933         case MVT::v8i16:
18934         case MVT::v8i32:
18935         case MVT::v16i16:
18936         case MVT::v16i32:
18937         case MVT::v8i64:
18938           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
18939         }
18940       case ISD::SRL:
18941         switch (VT.SimpleTy) {
18942         default: return SDValue();
18943         case MVT::v2i64:
18944         case MVT::v4i32:
18945         case MVT::v8i16:
18946         case MVT::v4i64:
18947         case MVT::v8i32:
18948         case MVT::v16i16:
18949         case MVT::v16i32:
18950         case MVT::v8i64:
18951           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
18952         }
18953       }
18954     }
18955   }
18956
18957   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18958   if (!Subtarget->is64Bit() &&
18959       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
18960       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
18961       Amt.getOpcode() == ISD::BITCAST &&
18962       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18963     Amt = Amt.getOperand(0);
18964     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18965                      VT.getVectorNumElements();
18966     std::vector<SDValue> Vals(Ratio);
18967     for (unsigned i = 0; i != Ratio; ++i)
18968       Vals[i] = Amt.getOperand(i);
18969     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18970       for (unsigned j = 0; j != Ratio; ++j)
18971         if (Vals[j] != Amt.getOperand(i + j))
18972           return SDValue();
18973     }
18974     switch (Op.getOpcode()) {
18975     default:
18976       llvm_unreachable("Unknown shift opcode!");
18977     case ISD::SHL:
18978       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
18979     case ISD::SRL:
18980       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
18981     case ISD::SRA:
18982       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
18983     }
18984   }
18985
18986   return SDValue();
18987 }
18988
18989 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18990                           SelectionDAG &DAG) {
18991   MVT VT = Op.getSimpleValueType();
18992   SDLoc dl(Op);
18993   SDValue R = Op.getOperand(0);
18994   SDValue Amt = Op.getOperand(1);
18995   SDValue V;
18996
18997   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18998   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18999
19000   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
19001   if (V.getNode())
19002     return V;
19003
19004   V = LowerScalarVariableShift(Op, DAG, Subtarget);
19005   if (V.getNode())
19006       return V;
19007
19008   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
19009     return Op;
19010   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
19011   if (Subtarget->hasInt256()) {
19012     if (Op.getOpcode() == ISD::SRL &&
19013         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
19014          VT == MVT::v4i64 || VT == MVT::v8i32))
19015       return Op;
19016     if (Op.getOpcode() == ISD::SHL &&
19017         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
19018          VT == MVT::v4i64 || VT == MVT::v8i32))
19019       return Op;
19020     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
19021       return Op;
19022   }
19023
19024   // If possible, lower this packed shift into a vector multiply instead of
19025   // expanding it into a sequence of scalar shifts.
19026   // Do this only if the vector shift count is a constant build_vector.
19027   if (Op.getOpcode() == ISD::SHL &&
19028       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
19029        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
19030       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
19031     SmallVector<SDValue, 8> Elts;
19032     EVT SVT = VT.getScalarType();
19033     unsigned SVTBits = SVT.getSizeInBits();
19034     const APInt &One = APInt(SVTBits, 1);
19035     unsigned NumElems = VT.getVectorNumElements();
19036
19037     for (unsigned i=0; i !=NumElems; ++i) {
19038       SDValue Op = Amt->getOperand(i);
19039       if (Op->getOpcode() == ISD::UNDEF) {
19040         Elts.push_back(Op);
19041         continue;
19042       }
19043
19044       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
19045       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
19046       uint64_t ShAmt = C.getZExtValue();
19047       if (ShAmt >= SVTBits) {
19048         Elts.push_back(DAG.getUNDEF(SVT));
19049         continue;
19050       }
19051       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
19052     }
19053     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
19054     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
19055   }
19056
19057   // Lower SHL with variable shift amount.
19058   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
19059     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
19060
19061     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
19062     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
19063     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
19064     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
19065   }
19066
19067   // If possible, lower this shift as a sequence of two shifts by
19068   // constant plus a MOVSS/MOVSD instead of scalarizing it.
19069   // Example:
19070   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
19071   //
19072   // Could be rewritten as:
19073   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
19074   //
19075   // The advantage is that the two shifts from the example would be
19076   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
19077   // the vector shift into four scalar shifts plus four pairs of vector
19078   // insert/extract.
19079   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
19080       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
19081     unsigned TargetOpcode = X86ISD::MOVSS;
19082     bool CanBeSimplified;
19083     // The splat value for the first packed shift (the 'X' from the example).
19084     SDValue Amt1 = Amt->getOperand(0);
19085     // The splat value for the second packed shift (the 'Y' from the example).
19086     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
19087                                         Amt->getOperand(2);
19088
19089     // See if it is possible to replace this node with a sequence of
19090     // two shifts followed by a MOVSS/MOVSD
19091     if (VT == MVT::v4i32) {
19092       // Check if it is legal to use a MOVSS.
19093       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
19094                         Amt2 == Amt->getOperand(3);
19095       if (!CanBeSimplified) {
19096         // Otherwise, check if we can still simplify this node using a MOVSD.
19097         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
19098                           Amt->getOperand(2) == Amt->getOperand(3);
19099         TargetOpcode = X86ISD::MOVSD;
19100         Amt2 = Amt->getOperand(2);
19101       }
19102     } else {
19103       // Do similar checks for the case where the machine value type
19104       // is MVT::v8i16.
19105       CanBeSimplified = Amt1 == Amt->getOperand(1);
19106       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
19107         CanBeSimplified = Amt2 == Amt->getOperand(i);
19108
19109       if (!CanBeSimplified) {
19110         TargetOpcode = X86ISD::MOVSD;
19111         CanBeSimplified = true;
19112         Amt2 = Amt->getOperand(4);
19113         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
19114           CanBeSimplified = Amt1 == Amt->getOperand(i);
19115         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
19116           CanBeSimplified = Amt2 == Amt->getOperand(j);
19117       }
19118     }
19119
19120     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
19121         isa<ConstantSDNode>(Amt2)) {
19122       // Replace this node with two shifts followed by a MOVSS/MOVSD.
19123       EVT CastVT = MVT::v4i32;
19124       SDValue Splat1 =
19125         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
19126       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
19127       SDValue Splat2 =
19128         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
19129       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
19130       if (TargetOpcode == X86ISD::MOVSD)
19131         CastVT = MVT::v2i64;
19132       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
19133       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
19134       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
19135                                             BitCast1, DAG);
19136       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
19137     }
19138   }
19139
19140   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
19141     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
19142
19143     // a = a << 5;
19144     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
19145     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
19146
19147     // Turn 'a' into a mask suitable for VSELECT
19148     SDValue VSelM = DAG.getConstant(0x80, VT);
19149     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
19150     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
19151
19152     SDValue CM1 = DAG.getConstant(0x0f, VT);
19153     SDValue CM2 = DAG.getConstant(0x3f, VT);
19154
19155     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
19156     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
19157     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
19158     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
19159     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
19160
19161     // a += a
19162     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
19163     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
19164     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
19165
19166     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
19167     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
19168     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
19169     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
19170     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
19171
19172     // a += a
19173     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
19174     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
19175     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
19176
19177     // return VSELECT(r, r+r, a);
19178     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
19179                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
19180     return R;
19181   }
19182
19183   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19184   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19185   // solution better.
19186   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19187     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
19188     unsigned ExtOpc =
19189         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19190     R = DAG.getNode(ExtOpc, dl, NewVT, R);
19191     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
19192     return DAG.getNode(ISD::TRUNCATE, dl, VT,
19193                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
19194     }
19195
19196   // Decompose 256-bit shifts into smaller 128-bit shifts.
19197   if (VT.is256BitVector()) {
19198     unsigned NumElems = VT.getVectorNumElements();
19199     MVT EltVT = VT.getVectorElementType();
19200     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19201
19202     // Extract the two vectors
19203     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19204     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19205
19206     // Recreate the shift amount vectors
19207     SDValue Amt1, Amt2;
19208     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19209       // Constant shift amount
19210       SmallVector<SDValue, 4> Amt1Csts;
19211       SmallVector<SDValue, 4> Amt2Csts;
19212       for (unsigned i = 0; i != NumElems/2; ++i)
19213         Amt1Csts.push_back(Amt->getOperand(i));
19214       for (unsigned i = NumElems/2; i != NumElems; ++i)
19215         Amt2Csts.push_back(Amt->getOperand(i));
19216
19217       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19218       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19219     } else {
19220       // Variable shift amount
19221       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19222       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19223     }
19224
19225     // Issue new vector shifts for the smaller types
19226     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19227     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19228
19229     // Concatenate the result back
19230     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19231   }
19232
19233   return SDValue();
19234 }
19235
19236 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19237   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19238   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19239   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19240   // has only one use.
19241   SDNode *N = Op.getNode();
19242   SDValue LHS = N->getOperand(0);
19243   SDValue RHS = N->getOperand(1);
19244   unsigned BaseOp = 0;
19245   unsigned Cond = 0;
19246   SDLoc DL(Op);
19247   switch (Op.getOpcode()) {
19248   default: llvm_unreachable("Unknown ovf instruction!");
19249   case ISD::SADDO:
19250     // A subtract of one will be selected as a INC. Note that INC doesn't
19251     // set CF, so we can't do this for UADDO.
19252     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
19253       if (C->isOne()) {
19254         BaseOp = X86ISD::INC;
19255         Cond = X86::COND_O;
19256         break;
19257       }
19258     BaseOp = X86ISD::ADD;
19259     Cond = X86::COND_O;
19260     break;
19261   case ISD::UADDO:
19262     BaseOp = X86ISD::ADD;
19263     Cond = X86::COND_B;
19264     break;
19265   case ISD::SSUBO:
19266     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19267     // set CF, so we can't do this for USUBO.
19268     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
19269       if (C->isOne()) {
19270         BaseOp = X86ISD::DEC;
19271         Cond = X86::COND_O;
19272         break;
19273       }
19274     BaseOp = X86ISD::SUB;
19275     Cond = X86::COND_O;
19276     break;
19277   case ISD::USUBO:
19278     BaseOp = X86ISD::SUB;
19279     Cond = X86::COND_B;
19280     break;
19281   case ISD::SMULO:
19282     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19283     Cond = X86::COND_O;
19284     break;
19285   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19286     if (N->getValueType(0) == MVT::i8) {
19287       BaseOp = X86ISD::UMUL8;
19288       Cond = X86::COND_O;
19289       break;
19290     }
19291     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19292                                  MVT::i32);
19293     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19294
19295     SDValue SetCC =
19296       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19297                   DAG.getConstant(X86::COND_O, MVT::i32),
19298                   SDValue(Sum.getNode(), 2));
19299
19300     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19301   }
19302   }
19303
19304   // Also sets EFLAGS.
19305   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19306   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19307
19308   SDValue SetCC =
19309     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19310                 DAG.getConstant(Cond, MVT::i32),
19311                 SDValue(Sum.getNode(), 1));
19312
19313   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19314 }
19315
19316 // Sign extension of the low part of vector elements. This may be used either
19317 // when sign extend instructions are not available or if the vector element
19318 // sizes already match the sign-extended size. If the vector elements are in
19319 // their pre-extended size and sign extend instructions are available, that will
19320 // be handled by LowerSIGN_EXTEND.
19321 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
19322                                                   SelectionDAG &DAG) const {
19323   SDLoc dl(Op);
19324   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
19325   MVT VT = Op.getSimpleValueType();
19326
19327   if (!Subtarget->hasSSE2() || !VT.isVector())
19328     return SDValue();
19329
19330   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
19331                       ExtraVT.getScalarType().getSizeInBits();
19332
19333   switch (VT.SimpleTy) {
19334     default: return SDValue();
19335     case MVT::v8i32:
19336     case MVT::v16i16:
19337       if (!Subtarget->hasFp256())
19338         return SDValue();
19339       if (!Subtarget->hasInt256()) {
19340         // needs to be split
19341         unsigned NumElems = VT.getVectorNumElements();
19342
19343         // Extract the LHS vectors
19344         SDValue LHS = Op.getOperand(0);
19345         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
19346         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
19347
19348         MVT EltVT = VT.getVectorElementType();
19349         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19350
19351         EVT ExtraEltVT = ExtraVT.getVectorElementType();
19352         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
19353         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
19354                                    ExtraNumElems/2);
19355         SDValue Extra = DAG.getValueType(ExtraVT);
19356
19357         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
19358         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
19359
19360         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
19361       }
19362       // fall through
19363     case MVT::v4i32:
19364     case MVT::v8i16: {
19365       SDValue Op0 = Op.getOperand(0);
19366
19367       // This is a sign extension of some low part of vector elements without
19368       // changing the size of the vector elements themselves:
19369       // Shift-Left + Shift-Right-Algebraic.
19370       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
19371                                                BitsDiff, DAG);
19372       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
19373                                         DAG);
19374     }
19375   }
19376 }
19377
19378 /// Returns true if the operand type is exactly twice the native width, and
19379 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19380 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19381 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19382 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
19383   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19384
19385   if (OpWidth == 64)
19386     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19387   else if (OpWidth == 128)
19388     return Subtarget->hasCmpxchg16b();
19389   else
19390     return false;
19391 }
19392
19393 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19394   return needsCmpXchgNb(SI->getValueOperand()->getType());
19395 }
19396
19397 // Note: this turns large loads into lock cmpxchg8b/16b.
19398 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19399 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19400   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19401   return needsCmpXchgNb(PTy->getElementType());
19402 }
19403
19404 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19405   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19406   const Type *MemType = AI->getType();
19407
19408   // If the operand is too big, we must see if cmpxchg8/16b is available
19409   // and default to library calls otherwise.
19410   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19411     return needsCmpXchgNb(MemType);
19412
19413   AtomicRMWInst::BinOp Op = AI->getOperation();
19414   switch (Op) {
19415   default:
19416     llvm_unreachable("Unknown atomic operation");
19417   case AtomicRMWInst::Xchg:
19418   case AtomicRMWInst::Add:
19419   case AtomicRMWInst::Sub:
19420     // It's better to use xadd, xsub or xchg for these in all cases.
19421     return false;
19422   case AtomicRMWInst::Or:
19423   case AtomicRMWInst::And:
19424   case AtomicRMWInst::Xor:
19425     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19426     // prefix to a normal instruction for these operations.
19427     return !AI->use_empty();
19428   case AtomicRMWInst::Nand:
19429   case AtomicRMWInst::Max:
19430   case AtomicRMWInst::Min:
19431   case AtomicRMWInst::UMax:
19432   case AtomicRMWInst::UMin:
19433     // These always require a non-trivial set of data operations on x86. We must
19434     // use a cmpxchg loop.
19435     return true;
19436   }
19437 }
19438
19439 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19440   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19441   // no-sse2). There isn't any reason to disable it if the target processor
19442   // supports it.
19443   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19444 }
19445
19446 LoadInst *
19447 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19448   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19449   const Type *MemType = AI->getType();
19450   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19451   // there is no benefit in turning such RMWs into loads, and it is actually
19452   // harmful as it introduces a mfence.
19453   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19454     return nullptr;
19455
19456   auto Builder = IRBuilder<>(AI);
19457   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19458   auto SynchScope = AI->getSynchScope();
19459   // We must restrict the ordering to avoid generating loads with Release or
19460   // ReleaseAcquire orderings.
19461   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19462   auto Ptr = AI->getPointerOperand();
19463
19464   // Before the load we need a fence. Here is an example lifted from
19465   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19466   // is required:
19467   // Thread 0:
19468   //   x.store(1, relaxed);
19469   //   r1 = y.fetch_add(0, release);
19470   // Thread 1:
19471   //   y.fetch_add(42, acquire);
19472   //   r2 = x.load(relaxed);
19473   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19474   // lowered to just a load without a fence. A mfence flushes the store buffer,
19475   // making the optimization clearly correct.
19476   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19477   // otherwise, we might be able to be more agressive on relaxed idempotent
19478   // rmw. In practice, they do not look useful, so we don't try to be
19479   // especially clever.
19480   if (SynchScope == SingleThread) {
19481     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19482     // the IR level, so we must wrap it in an intrinsic.
19483     return nullptr;
19484   } else if (hasMFENCE(*Subtarget)) {
19485     Function *MFence = llvm::Intrinsic::getDeclaration(M,
19486             Intrinsic::x86_sse2_mfence);
19487     Builder.CreateCall(MFence);
19488   } else {
19489     // FIXME: it might make sense to use a locked operation here but on a
19490     // different cache-line to prevent cache-line bouncing. In practice it
19491     // is probably a small win, and x86 processors without mfence are rare
19492     // enough that we do not bother.
19493     return nullptr;
19494   }
19495
19496   // Finally we can emit the atomic load.
19497   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19498           AI->getType()->getPrimitiveSizeInBits());
19499   Loaded->setAtomic(Order, SynchScope);
19500   AI->replaceAllUsesWith(Loaded);
19501   AI->eraseFromParent();
19502   return Loaded;
19503 }
19504
19505 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19506                                  SelectionDAG &DAG) {
19507   SDLoc dl(Op);
19508   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19509     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19510   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19511     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19512
19513   // The only fence that needs an instruction is a sequentially-consistent
19514   // cross-thread fence.
19515   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19516     if (hasMFENCE(*Subtarget))
19517       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19518
19519     SDValue Chain = Op.getOperand(0);
19520     SDValue Zero = DAG.getConstant(0, MVT::i32);
19521     SDValue Ops[] = {
19522       DAG.getRegister(X86::ESP, MVT::i32), // Base
19523       DAG.getTargetConstant(1, MVT::i8),   // Scale
19524       DAG.getRegister(0, MVT::i32),        // Index
19525       DAG.getTargetConstant(0, MVT::i32),  // Disp
19526       DAG.getRegister(0, MVT::i32),        // Segment.
19527       Zero,
19528       Chain
19529     };
19530     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19531     return SDValue(Res, 0);
19532   }
19533
19534   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19535   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19536 }
19537
19538 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19539                              SelectionDAG &DAG) {
19540   MVT T = Op.getSimpleValueType();
19541   SDLoc DL(Op);
19542   unsigned Reg = 0;
19543   unsigned size = 0;
19544   switch(T.SimpleTy) {
19545   default: llvm_unreachable("Invalid value type!");
19546   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19547   case MVT::i16: Reg = X86::AX;  size = 2; break;
19548   case MVT::i32: Reg = X86::EAX; size = 4; break;
19549   case MVT::i64:
19550     assert(Subtarget->is64Bit() && "Node not type legal!");
19551     Reg = X86::RAX; size = 8;
19552     break;
19553   }
19554   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19555                                   Op.getOperand(2), SDValue());
19556   SDValue Ops[] = { cpIn.getValue(0),
19557                     Op.getOperand(1),
19558                     Op.getOperand(3),
19559                     DAG.getTargetConstant(size, MVT::i8),
19560                     cpIn.getValue(1) };
19561   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19562   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19563   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19564                                            Ops, T, MMO);
19565
19566   SDValue cpOut =
19567     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19568   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19569                                       MVT::i32, cpOut.getValue(2));
19570   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19571                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19572
19573   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19574   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19575   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19576   return SDValue();
19577 }
19578
19579 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19580                             SelectionDAG &DAG) {
19581   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19582   MVT DstVT = Op.getSimpleValueType();
19583
19584   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19585     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19586     if (DstVT != MVT::f64)
19587       // This conversion needs to be expanded.
19588       return SDValue();
19589
19590     SDValue InVec = Op->getOperand(0);
19591     SDLoc dl(Op);
19592     unsigned NumElts = SrcVT.getVectorNumElements();
19593     EVT SVT = SrcVT.getVectorElementType();
19594
19595     // Widen the vector in input in the case of MVT::v2i32.
19596     // Example: from MVT::v2i32 to MVT::v4i32.
19597     SmallVector<SDValue, 16> Elts;
19598     for (unsigned i = 0, e = NumElts; i != e; ++i)
19599       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19600                                  DAG.getIntPtrConstant(i)));
19601
19602     // Explicitly mark the extra elements as Undef.
19603     SDValue Undef = DAG.getUNDEF(SVT);
19604     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
19605       Elts.push_back(Undef);
19606
19607     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19608     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19609     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
19610     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19611                        DAG.getIntPtrConstant(0));
19612   }
19613
19614   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19615          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19616   assert((DstVT == MVT::i64 ||
19617           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19618          "Unexpected custom BITCAST");
19619   // i64 <=> MMX conversions are Legal.
19620   if (SrcVT==MVT::i64 && DstVT.isVector())
19621     return Op;
19622   if (DstVT==MVT::i64 && SrcVT.isVector())
19623     return Op;
19624   // MMX <=> MMX conversions are Legal.
19625   if (SrcVT.isVector() && DstVT.isVector())
19626     return Op;
19627   // All other conversions need to be expanded.
19628   return SDValue();
19629 }
19630
19631 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19632                           SelectionDAG &DAG) {
19633   SDNode *Node = Op.getNode();
19634   SDLoc dl(Node);
19635
19636   Op = Op.getOperand(0);
19637   EVT VT = Op.getValueType();
19638   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19639          "CTPOP lowering only implemented for 128/256-bit wide vector types");
19640
19641   unsigned NumElts = VT.getVectorNumElements();
19642   EVT EltVT = VT.getVectorElementType();
19643   unsigned Len = EltVT.getSizeInBits();
19644
19645   // This is the vectorized version of the "best" algorithm from
19646   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19647   // with a minor tweak to use a series of adds + shifts instead of vector
19648   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
19649   //
19650   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
19651   //  v8i32 => Always profitable
19652   //
19653   // FIXME: There a couple of possible improvements:
19654   //
19655   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
19656   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
19657   //
19658   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
19659          "CTPOP not implemented for this vector element type.");
19660
19661   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
19662   // extra legalization.
19663   bool NeedsBitcast = EltVT == MVT::i32;
19664   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
19665
19666   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
19667   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
19668   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
19669
19670   // v = v - ((v >> 1) & 0x55555555...)
19671   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
19672   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
19673   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
19674   if (NeedsBitcast)
19675     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
19676
19677   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
19678   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
19679   if (NeedsBitcast)
19680     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
19681
19682   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
19683   if (VT != And.getValueType())
19684     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19685   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
19686
19687   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19688   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
19689   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
19690   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
19691   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
19692
19693   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
19694   if (NeedsBitcast) {
19695     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
19696     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
19697     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
19698   }
19699
19700   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
19701   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
19702   if (VT != AndRHS.getValueType()) {
19703     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
19704     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
19705   }
19706   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
19707
19708   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19709   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
19710   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
19711   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
19712   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
19713
19714   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
19715   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
19716   if (NeedsBitcast) {
19717     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
19718     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
19719   }
19720   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
19721   if (VT != And.getValueType())
19722     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19723
19724   // The algorithm mentioned above uses:
19725   //    v = (v * 0x01010101...) >> (Len - 8)
19726   //
19727   // Change it to use vector adds + vector shifts which yield faster results on
19728   // Haswell than using vector integer multiplication.
19729   //
19730   // For i32 elements:
19731   //    v = v + (v >> 8)
19732   //    v = v + (v >> 16)
19733   //
19734   // For i64 elements:
19735   //    v = v + (v >> 8)
19736   //    v = v + (v >> 16)
19737   //    v = v + (v >> 32)
19738   //
19739   Add = And;
19740   SmallVector<SDValue, 8> Csts;
19741   for (unsigned i = 8; i <= Len/2; i *= 2) {
19742     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
19743     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
19744     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
19745     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
19746     Csts.clear();
19747   }
19748
19749   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
19750   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
19751   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
19752   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
19753   if (NeedsBitcast) {
19754     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
19755     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
19756   }
19757   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
19758   if (VT != And.getValueType())
19759     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19760
19761   return And;
19762 }
19763
19764 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19765   SDNode *Node = Op.getNode();
19766   SDLoc dl(Node);
19767   EVT T = Node->getValueType(0);
19768   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19769                               DAG.getConstant(0, T), Node->getOperand(2));
19770   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19771                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19772                        Node->getOperand(0),
19773                        Node->getOperand(1), negOp,
19774                        cast<AtomicSDNode>(Node)->getMemOperand(),
19775                        cast<AtomicSDNode>(Node)->getOrdering(),
19776                        cast<AtomicSDNode>(Node)->getSynchScope());
19777 }
19778
19779 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19780   SDNode *Node = Op.getNode();
19781   SDLoc dl(Node);
19782   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19783
19784   // Convert seq_cst store -> xchg
19785   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19786   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19787   //        (The only way to get a 16-byte store is cmpxchg16b)
19788   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19789   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19790       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19791     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19792                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19793                                  Node->getOperand(0),
19794                                  Node->getOperand(1), Node->getOperand(2),
19795                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19796                                  cast<AtomicSDNode>(Node)->getOrdering(),
19797                                  cast<AtomicSDNode>(Node)->getSynchScope());
19798     return Swap.getValue(1);
19799   }
19800   // Other atomic stores have a simple pattern.
19801   return Op;
19802 }
19803
19804 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19805   EVT VT = Op.getNode()->getSimpleValueType(0);
19806
19807   // Let legalize expand this if it isn't a legal type yet.
19808   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19809     return SDValue();
19810
19811   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19812
19813   unsigned Opc;
19814   bool ExtraOp = false;
19815   switch (Op.getOpcode()) {
19816   default: llvm_unreachable("Invalid code");
19817   case ISD::ADDC: Opc = X86ISD::ADD; break;
19818   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19819   case ISD::SUBC: Opc = X86ISD::SUB; break;
19820   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19821   }
19822
19823   if (!ExtraOp)
19824     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19825                        Op.getOperand(1));
19826   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19827                      Op.getOperand(1), Op.getOperand(2));
19828 }
19829
19830 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19831                             SelectionDAG &DAG) {
19832   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19833
19834   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19835   // which returns the values as { float, float } (in XMM0) or
19836   // { double, double } (which is returned in XMM0, XMM1).
19837   SDLoc dl(Op);
19838   SDValue Arg = Op.getOperand(0);
19839   EVT ArgVT = Arg.getValueType();
19840   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19841
19842   TargetLowering::ArgListTy Args;
19843   TargetLowering::ArgListEntry Entry;
19844
19845   Entry.Node = Arg;
19846   Entry.Ty = ArgTy;
19847   Entry.isSExt = false;
19848   Entry.isZExt = false;
19849   Args.push_back(Entry);
19850
19851   bool isF64 = ArgVT == MVT::f64;
19852   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19853   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19854   // the results are returned via SRet in memory.
19855   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19856   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19857   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
19858
19859   Type *RetTy = isF64
19860     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19861     : (Type*)VectorType::get(ArgTy, 4);
19862
19863   TargetLowering::CallLoweringInfo CLI(DAG);
19864   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19865     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19866
19867   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19868
19869   if (isF64)
19870     // Returned in xmm0 and xmm1.
19871     return CallResult.first;
19872
19873   // Returned in bits 0:31 and 32:64 xmm0.
19874   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19875                                CallResult.first, DAG.getIntPtrConstant(0));
19876   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19877                                CallResult.first, DAG.getIntPtrConstant(1));
19878   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19879   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19880 }
19881
19882 /// LowerOperation - Provide custom lowering hooks for some operations.
19883 ///
19884 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19885   switch (Op.getOpcode()) {
19886   default: llvm_unreachable("Should not custom lower this!");
19887   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
19888   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19889   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19890     return LowerCMP_SWAP(Op, Subtarget, DAG);
19891   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19892   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19893   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19894   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19895   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
19896   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
19897   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19898   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19899   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19900   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19901   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19902   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19903   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19904   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19905   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19906   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19907   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19908   case ISD::SHL_PARTS:
19909   case ISD::SRA_PARTS:
19910   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19911   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19912   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19913   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19914   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19915   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19916   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19917   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19918   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19919   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19920   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19921   case ISD::FABS:
19922   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19923   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19924   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19925   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19926   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19927   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19928   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19929   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19930   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19931   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19932   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19933   case ISD::INTRINSIC_VOID:
19934   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19935   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19936   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19937   case ISD::FRAME_TO_ARGS_OFFSET:
19938                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19939   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19940   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19941   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19942   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19943   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19944   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19945   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19946   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19947   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19948   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
19949   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19950   case ISD::UMUL_LOHI:
19951   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19952   case ISD::SRA:
19953   case ISD::SRL:
19954   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19955   case ISD::SADDO:
19956   case ISD::UADDO:
19957   case ISD::SSUBO:
19958   case ISD::USUBO:
19959   case ISD::SMULO:
19960   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19961   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19962   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19963   case ISD::ADDC:
19964   case ISD::ADDE:
19965   case ISD::SUBC:
19966   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19967   case ISD::ADD:                return LowerADD(Op, DAG);
19968   case ISD::SUB:                return LowerSUB(Op, DAG);
19969   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19970   }
19971 }
19972
19973 /// ReplaceNodeResults - Replace a node with an illegal result type
19974 /// with a new node built out of custom code.
19975 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19976                                            SmallVectorImpl<SDValue>&Results,
19977                                            SelectionDAG &DAG) const {
19978   SDLoc dl(N);
19979   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19980   switch (N->getOpcode()) {
19981   default:
19982     llvm_unreachable("Do not know how to custom type legalize this operation!");
19983   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19984   case X86ISD::FMINC:
19985   case X86ISD::FMIN:
19986   case X86ISD::FMAXC:
19987   case X86ISD::FMAX: {
19988     EVT VT = N->getValueType(0);
19989     if (VT != MVT::v2f32)
19990       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19991     SDValue UNDEF = DAG.getUNDEF(VT);
19992     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19993                               N->getOperand(0), UNDEF);
19994     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19995                               N->getOperand(1), UNDEF);
19996     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19997     return;
19998   }
19999   case ISD::SIGN_EXTEND_INREG:
20000   case ISD::ADDC:
20001   case ISD::ADDE:
20002   case ISD::SUBC:
20003   case ISD::SUBE:
20004     // We don't want to expand or promote these.
20005     return;
20006   case ISD::SDIV:
20007   case ISD::UDIV:
20008   case ISD::SREM:
20009   case ISD::UREM:
20010   case ISD::SDIVREM:
20011   case ISD::UDIVREM: {
20012     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20013     Results.push_back(V);
20014     return;
20015   }
20016   case ISD::FP_TO_SINT:
20017   case ISD::FP_TO_UINT: {
20018     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20019
20020     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
20021       return;
20022
20023     std::pair<SDValue,SDValue> Vals =
20024         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20025     SDValue FIST = Vals.first, StackSlot = Vals.second;
20026     if (FIST.getNode()) {
20027       EVT VT = N->getValueType(0);
20028       // Return a load from the stack slot.
20029       if (StackSlot.getNode())
20030         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20031                                       MachinePointerInfo(),
20032                                       false, false, false, 0));
20033       else
20034         Results.push_back(FIST);
20035     }
20036     return;
20037   }
20038   case ISD::UINT_TO_FP: {
20039     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20040     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20041         N->getValueType(0) != MVT::v2f32)
20042       return;
20043     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20044                                  N->getOperand(0));
20045     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
20046                                      MVT::f64);
20047     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20048     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20049                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
20050     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
20051     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20052     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20053     return;
20054   }
20055   case ISD::FP_ROUND: {
20056     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20057         return;
20058     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20059     Results.push_back(V);
20060     return;
20061   }
20062   case ISD::INTRINSIC_W_CHAIN: {
20063     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20064     switch (IntNo) {
20065     default : llvm_unreachable("Do not know how to custom type "
20066                                "legalize this intrinsic operation!");
20067     case Intrinsic::x86_rdtsc:
20068       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20069                                      Results);
20070     case Intrinsic::x86_rdtscp:
20071       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20072                                      Results);
20073     case Intrinsic::x86_rdpmc:
20074       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20075     }
20076   }
20077   case ISD::READCYCLECOUNTER: {
20078     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20079                                    Results);
20080   }
20081   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20082     EVT T = N->getValueType(0);
20083     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20084     bool Regs64bit = T == MVT::i128;
20085     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20086     SDValue cpInL, cpInH;
20087     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20088                         DAG.getConstant(0, HalfT));
20089     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20090                         DAG.getConstant(1, HalfT));
20091     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20092                              Regs64bit ? X86::RAX : X86::EAX,
20093                              cpInL, SDValue());
20094     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20095                              Regs64bit ? X86::RDX : X86::EDX,
20096                              cpInH, cpInL.getValue(1));
20097     SDValue swapInL, swapInH;
20098     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20099                           DAG.getConstant(0, HalfT));
20100     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20101                           DAG.getConstant(1, HalfT));
20102     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20103                                Regs64bit ? X86::RBX : X86::EBX,
20104                                swapInL, cpInH.getValue(1));
20105     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20106                                Regs64bit ? X86::RCX : X86::ECX,
20107                                swapInH, swapInL.getValue(1));
20108     SDValue Ops[] = { swapInH.getValue(0),
20109                       N->getOperand(1),
20110                       swapInH.getValue(1) };
20111     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20112     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20113     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20114                                   X86ISD::LCMPXCHG8_DAG;
20115     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20116     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20117                                         Regs64bit ? X86::RAX : X86::EAX,
20118                                         HalfT, Result.getValue(1));
20119     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20120                                         Regs64bit ? X86::RDX : X86::EDX,
20121                                         HalfT, cpOutL.getValue(2));
20122     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20123
20124     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20125                                         MVT::i32, cpOutH.getValue(2));
20126     SDValue Success =
20127         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20128                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
20129     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20130
20131     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20132     Results.push_back(Success);
20133     Results.push_back(EFLAGS.getValue(1));
20134     return;
20135   }
20136   case ISD::ATOMIC_SWAP:
20137   case ISD::ATOMIC_LOAD_ADD:
20138   case ISD::ATOMIC_LOAD_SUB:
20139   case ISD::ATOMIC_LOAD_AND:
20140   case ISD::ATOMIC_LOAD_OR:
20141   case ISD::ATOMIC_LOAD_XOR:
20142   case ISD::ATOMIC_LOAD_NAND:
20143   case ISD::ATOMIC_LOAD_MIN:
20144   case ISD::ATOMIC_LOAD_MAX:
20145   case ISD::ATOMIC_LOAD_UMIN:
20146   case ISD::ATOMIC_LOAD_UMAX:
20147   case ISD::ATOMIC_LOAD: {
20148     // Delegate to generic TypeLegalization. Situations we can really handle
20149     // should have already been dealt with by AtomicExpandPass.cpp.
20150     break;
20151   }
20152   case ISD::BITCAST: {
20153     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20154     EVT DstVT = N->getValueType(0);
20155     EVT SrcVT = N->getOperand(0)->getValueType(0);
20156
20157     if (SrcVT != MVT::f64 ||
20158         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20159       return;
20160
20161     unsigned NumElts = DstVT.getVectorNumElements();
20162     EVT SVT = DstVT.getVectorElementType();
20163     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20164     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20165                                    MVT::v2f64, N->getOperand(0));
20166     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
20167
20168     if (ExperimentalVectorWideningLegalization) {
20169       // If we are legalizing vectors by widening, we already have the desired
20170       // legal vector type, just return it.
20171       Results.push_back(ToVecInt);
20172       return;
20173     }
20174
20175     SmallVector<SDValue, 8> Elts;
20176     for (unsigned i = 0, e = NumElts; i != e; ++i)
20177       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20178                                    ToVecInt, DAG.getIntPtrConstant(i)));
20179
20180     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20181   }
20182   }
20183 }
20184
20185 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20186   switch (Opcode) {
20187   default: return nullptr;
20188   case X86ISD::BSF:                return "X86ISD::BSF";
20189   case X86ISD::BSR:                return "X86ISD::BSR";
20190   case X86ISD::SHLD:               return "X86ISD::SHLD";
20191   case X86ISD::SHRD:               return "X86ISD::SHRD";
20192   case X86ISD::FAND:               return "X86ISD::FAND";
20193   case X86ISD::FANDN:              return "X86ISD::FANDN";
20194   case X86ISD::FOR:                return "X86ISD::FOR";
20195   case X86ISD::FXOR:               return "X86ISD::FXOR";
20196   case X86ISD::FSRL:               return "X86ISD::FSRL";
20197   case X86ISD::FILD:               return "X86ISD::FILD";
20198   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20199   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20200   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20201   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20202   case X86ISD::FLD:                return "X86ISD::FLD";
20203   case X86ISD::FST:                return "X86ISD::FST";
20204   case X86ISD::CALL:               return "X86ISD::CALL";
20205   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20206   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20207   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20208   case X86ISD::BT:                 return "X86ISD::BT";
20209   case X86ISD::CMP:                return "X86ISD::CMP";
20210   case X86ISD::COMI:               return "X86ISD::COMI";
20211   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20212   case X86ISD::CMPM:               return "X86ISD::CMPM";
20213   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20214   case X86ISD::SETCC:              return "X86ISD::SETCC";
20215   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20216   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20217   case X86ISD::CMOV:               return "X86ISD::CMOV";
20218   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20219   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20220   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20221   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20222   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20223   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20224   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20225   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20226   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20227   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20228   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20229   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20230   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20231   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20232   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20233   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20234   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20235   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20236   case X86ISD::HADD:               return "X86ISD::HADD";
20237   case X86ISD::HSUB:               return "X86ISD::HSUB";
20238   case X86ISD::FHADD:              return "X86ISD::FHADD";
20239   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20240   case X86ISD::UMAX:               return "X86ISD::UMAX";
20241   case X86ISD::UMIN:               return "X86ISD::UMIN";
20242   case X86ISD::SMAX:               return "X86ISD::SMAX";
20243   case X86ISD::SMIN:               return "X86ISD::SMIN";
20244   case X86ISD::FMAX:               return "X86ISD::FMAX";
20245   case X86ISD::FMIN:               return "X86ISD::FMIN";
20246   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20247   case X86ISD::FMINC:              return "X86ISD::FMINC";
20248   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20249   case X86ISD::FRCP:               return "X86ISD::FRCP";
20250   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20251   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20252   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20253   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20254   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20255   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20256   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20257   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20258   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20259   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20260   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20261   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20262   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20263   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20264   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20265   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20266   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20267   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
20268   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20269   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20270   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20271   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20272   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20273   case X86ISD::VSHL:               return "X86ISD::VSHL";
20274   case X86ISD::VSRL:               return "X86ISD::VSRL";
20275   case X86ISD::VSRA:               return "X86ISD::VSRA";
20276   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20277   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20278   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20279   case X86ISD::CMPP:               return "X86ISD::CMPP";
20280   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20281   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20282   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20283   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20284   case X86ISD::ADD:                return "X86ISD::ADD";
20285   case X86ISD::SUB:                return "X86ISD::SUB";
20286   case X86ISD::ADC:                return "X86ISD::ADC";
20287   case X86ISD::SBB:                return "X86ISD::SBB";
20288   case X86ISD::SMUL:               return "X86ISD::SMUL";
20289   case X86ISD::UMUL:               return "X86ISD::UMUL";
20290   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20291   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20292   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20293   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20294   case X86ISD::INC:                return "X86ISD::INC";
20295   case X86ISD::DEC:                return "X86ISD::DEC";
20296   case X86ISD::OR:                 return "X86ISD::OR";
20297   case X86ISD::XOR:                return "X86ISD::XOR";
20298   case X86ISD::AND:                return "X86ISD::AND";
20299   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20300   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20301   case X86ISD::PTEST:              return "X86ISD::PTEST";
20302   case X86ISD::TESTP:              return "X86ISD::TESTP";
20303   case X86ISD::TESTM:              return "X86ISD::TESTM";
20304   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20305   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20306   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20307   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20308   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20309   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20310   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20311   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20312   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20313   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20314   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20315   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20316   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20317   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20318   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20319   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20320   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20321   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20322   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20323   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20324   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20325   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20326   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20327   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20328   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20329   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20330   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20331   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20332   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20333   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20334   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20335   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20336   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20337   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20338   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20339   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20340   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20341   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20342   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
20343   case X86ISD::SAHF:               return "X86ISD::SAHF";
20344   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20345   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20346   case X86ISD::FMADD:              return "X86ISD::FMADD";
20347   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20348   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20349   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20350   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20351   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20352   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20353   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20354   case X86ISD::XTEST:              return "X86ISD::XTEST";
20355   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20356   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20357   case X86ISD::SELECT:             return "X86ISD::SELECT";
20358   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20359   case X86ISD::RCP28:              return "X86ISD::RCP28";
20360   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20361   }
20362 }
20363
20364 // isLegalAddressingMode - Return true if the addressing mode represented
20365 // by AM is legal for this target, for a load/store of the specified type.
20366 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
20367                                               Type *Ty) const {
20368   // X86 supports extremely general addressing modes.
20369   CodeModel::Model M = getTargetMachine().getCodeModel();
20370   Reloc::Model R = getTargetMachine().getRelocationModel();
20371
20372   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20373   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20374     return false;
20375
20376   if (AM.BaseGV) {
20377     unsigned GVFlags =
20378       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20379
20380     // If a reference to this global requires an extra load, we can't fold it.
20381     if (isGlobalStubReference(GVFlags))
20382       return false;
20383
20384     // If BaseGV requires a register for the PIC base, we cannot also have a
20385     // BaseReg specified.
20386     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20387       return false;
20388
20389     // If lower 4G is not available, then we must use rip-relative addressing.
20390     if ((M != CodeModel::Small || R != Reloc::Static) &&
20391         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20392       return false;
20393   }
20394
20395   switch (AM.Scale) {
20396   case 0:
20397   case 1:
20398   case 2:
20399   case 4:
20400   case 8:
20401     // These scales always work.
20402     break;
20403   case 3:
20404   case 5:
20405   case 9:
20406     // These scales are formed with basereg+scalereg.  Only accept if there is
20407     // no basereg yet.
20408     if (AM.HasBaseReg)
20409       return false;
20410     break;
20411   default:  // Other stuff never works.
20412     return false;
20413   }
20414
20415   return true;
20416 }
20417
20418 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20419   unsigned Bits = Ty->getScalarSizeInBits();
20420
20421   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20422   // particularly cheaper than those without.
20423   if (Bits == 8)
20424     return false;
20425
20426   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20427   // variable shifts just as cheap as scalar ones.
20428   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20429     return false;
20430
20431   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20432   // fully general vector.
20433   return true;
20434 }
20435
20436 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20437   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20438     return false;
20439   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20440   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20441   return NumBits1 > NumBits2;
20442 }
20443
20444 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20445   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20446     return false;
20447
20448   if (!isTypeLegal(EVT::getEVT(Ty1)))
20449     return false;
20450
20451   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20452
20453   // Assuming the caller doesn't have a zeroext or signext return parameter,
20454   // truncation all the way down to i1 is valid.
20455   return true;
20456 }
20457
20458 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20459   return isInt<32>(Imm);
20460 }
20461
20462 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20463   // Can also use sub to handle negated immediates.
20464   return isInt<32>(Imm);
20465 }
20466
20467 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20468   if (!VT1.isInteger() || !VT2.isInteger())
20469     return false;
20470   unsigned NumBits1 = VT1.getSizeInBits();
20471   unsigned NumBits2 = VT2.getSizeInBits();
20472   return NumBits1 > NumBits2;
20473 }
20474
20475 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20476   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20477   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20478 }
20479
20480 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20481   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20482   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20483 }
20484
20485 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20486   EVT VT1 = Val.getValueType();
20487   if (isZExtFree(VT1, VT2))
20488     return true;
20489
20490   if (Val.getOpcode() != ISD::LOAD)
20491     return false;
20492
20493   if (!VT1.isSimple() || !VT1.isInteger() ||
20494       !VT2.isSimple() || !VT2.isInteger())
20495     return false;
20496
20497   switch (VT1.getSimpleVT().SimpleTy) {
20498   default: break;
20499   case MVT::i8:
20500   case MVT::i16:
20501   case MVT::i32:
20502     // X86 has 8, 16, and 32-bit zero-extending loads.
20503     return true;
20504   }
20505
20506   return false;
20507 }
20508
20509 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20510
20511 bool
20512 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20513   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
20514     return false;
20515
20516   VT = VT.getScalarType();
20517
20518   if (!VT.isSimple())
20519     return false;
20520
20521   switch (VT.getSimpleVT().SimpleTy) {
20522   case MVT::f32:
20523   case MVT::f64:
20524     return true;
20525   default:
20526     break;
20527   }
20528
20529   return false;
20530 }
20531
20532 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20533   // i16 instructions are longer (0x66 prefix) and potentially slower.
20534   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20535 }
20536
20537 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20538 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20539 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20540 /// are assumed to be legal.
20541 bool
20542 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20543                                       EVT VT) const {
20544   if (!VT.isSimple())
20545     return false;
20546
20547   MVT SVT = VT.getSimpleVT();
20548
20549   // Very little shuffling can be done for 64-bit vectors right now.
20550   if (VT.getSizeInBits() == 64)
20551     return false;
20552
20553   // This is an experimental legality test that is tailored to match the
20554   // legality test of the experimental lowering more closely. They are gated
20555   // separately to ease testing of performance differences.
20556   if (ExperimentalVectorShuffleLegality)
20557     // We only care that the types being shuffled are legal. The lowering can
20558     // handle any possible shuffle mask that results.
20559     return isTypeLegal(SVT);
20560
20561   // If this is a single-input shuffle with no 128 bit lane crossings we can
20562   // lower it into pshufb.
20563   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
20564       (SVT.is256BitVector() && Subtarget->hasInt256())) {
20565     bool isLegal = true;
20566     for (unsigned I = 0, E = M.size(); I != E; ++I) {
20567       if (M[I] >= (int)SVT.getVectorNumElements() ||
20568           ShuffleCrosses128bitLane(SVT, I, M[I])) {
20569         isLegal = false;
20570         break;
20571       }
20572     }
20573     if (isLegal)
20574       return true;
20575   }
20576
20577   // FIXME: blends, shifts.
20578   return (SVT.getVectorNumElements() == 2 ||
20579           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
20580           isMOVLMask(M, SVT) ||
20581           isCommutedMOVLMask(M, SVT) ||
20582           isMOVHLPSMask(M, SVT) ||
20583           isSHUFPMask(M, SVT) ||
20584           isSHUFPMask(M, SVT, /* Commuted */ true) ||
20585           isPSHUFDMask(M, SVT) ||
20586           isPSHUFDMask(M, SVT, /* SecondOperand */ true) ||
20587           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
20588           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
20589           isPALIGNRMask(M, SVT, Subtarget) ||
20590           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
20591           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
20592           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
20593           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
20594           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()) ||
20595           (Subtarget->hasSSE41() && isINSERTPSMask(M, SVT)));
20596 }
20597
20598 bool
20599 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20600                                           EVT VT) const {
20601   if (!VT.isSimple())
20602     return false;
20603
20604   MVT SVT = VT.getSimpleVT();
20605
20606   // This is an experimental legality test that is tailored to match the
20607   // legality test of the experimental lowering more closely. They are gated
20608   // separately to ease testing of performance differences.
20609   if (ExperimentalVectorShuffleLegality)
20610     // The new vector shuffle lowering is very good at managing zero-inputs.
20611     return isShuffleMaskLegal(Mask, VT);
20612
20613   unsigned NumElts = SVT.getVectorNumElements();
20614   // FIXME: This collection of masks seems suspect.
20615   if (NumElts == 2)
20616     return true;
20617   if (NumElts == 4 && SVT.is128BitVector()) {
20618     return (isMOVLMask(Mask, SVT)  ||
20619             isCommutedMOVLMask(Mask, SVT, true) ||
20620             isSHUFPMask(Mask, SVT) ||
20621             isSHUFPMask(Mask, SVT, /* Commuted */ true) ||
20622             isBlendMask(Mask, SVT, Subtarget->hasSSE41(),
20623                         Subtarget->hasInt256()));
20624   }
20625   return false;
20626 }
20627
20628 //===----------------------------------------------------------------------===//
20629 //                           X86 Scheduler Hooks
20630 //===----------------------------------------------------------------------===//
20631
20632 /// Utility function to emit xbegin specifying the start of an RTM region.
20633 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20634                                      const TargetInstrInfo *TII) {
20635   DebugLoc DL = MI->getDebugLoc();
20636
20637   const BasicBlock *BB = MBB->getBasicBlock();
20638   MachineFunction::iterator I = MBB;
20639   ++I;
20640
20641   // For the v = xbegin(), we generate
20642   //
20643   // thisMBB:
20644   //  xbegin sinkMBB
20645   //
20646   // mainMBB:
20647   //  eax = -1
20648   //
20649   // sinkMBB:
20650   //  v = eax
20651
20652   MachineBasicBlock *thisMBB = MBB;
20653   MachineFunction *MF = MBB->getParent();
20654   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20655   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20656   MF->insert(I, mainMBB);
20657   MF->insert(I, sinkMBB);
20658
20659   // Transfer the remainder of BB and its successor edges to sinkMBB.
20660   sinkMBB->splice(sinkMBB->begin(), MBB,
20661                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20662   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20663
20664   // thisMBB:
20665   //  xbegin sinkMBB
20666   //  # fallthrough to mainMBB
20667   //  # abortion to sinkMBB
20668   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20669   thisMBB->addSuccessor(mainMBB);
20670   thisMBB->addSuccessor(sinkMBB);
20671
20672   // mainMBB:
20673   //  EAX = -1
20674   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20675   mainMBB->addSuccessor(sinkMBB);
20676
20677   // sinkMBB:
20678   // EAX is live into the sinkMBB
20679   sinkMBB->addLiveIn(X86::EAX);
20680   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20681           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20682     .addReg(X86::EAX);
20683
20684   MI->eraseFromParent();
20685   return sinkMBB;
20686 }
20687
20688 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20689 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20690 // in the .td file.
20691 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20692                                        const TargetInstrInfo *TII) {
20693   unsigned Opc;
20694   switch (MI->getOpcode()) {
20695   default: llvm_unreachable("illegal opcode!");
20696   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20697   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20698   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20699   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20700   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20701   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20702   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20703   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20704   }
20705
20706   DebugLoc dl = MI->getDebugLoc();
20707   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20708
20709   unsigned NumArgs = MI->getNumOperands();
20710   for (unsigned i = 1; i < NumArgs; ++i) {
20711     MachineOperand &Op = MI->getOperand(i);
20712     if (!(Op.isReg() && Op.isImplicit()))
20713       MIB.addOperand(Op);
20714   }
20715   if (MI->hasOneMemOperand())
20716     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20717
20718   BuildMI(*BB, MI, dl,
20719     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20720     .addReg(X86::XMM0);
20721
20722   MI->eraseFromParent();
20723   return BB;
20724 }
20725
20726 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20727 // defs in an instruction pattern
20728 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20729                                        const TargetInstrInfo *TII) {
20730   unsigned Opc;
20731   switch (MI->getOpcode()) {
20732   default: llvm_unreachable("illegal opcode!");
20733   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20734   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20735   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20736   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20737   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20738   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20739   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20740   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20741   }
20742
20743   DebugLoc dl = MI->getDebugLoc();
20744   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20745
20746   unsigned NumArgs = MI->getNumOperands(); // remove the results
20747   for (unsigned i = 1; i < NumArgs; ++i) {
20748     MachineOperand &Op = MI->getOperand(i);
20749     if (!(Op.isReg() && Op.isImplicit()))
20750       MIB.addOperand(Op);
20751   }
20752   if (MI->hasOneMemOperand())
20753     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20754
20755   BuildMI(*BB, MI, dl,
20756     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20757     .addReg(X86::ECX);
20758
20759   MI->eraseFromParent();
20760   return BB;
20761 }
20762
20763 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20764                                       const X86Subtarget *Subtarget) {
20765   DebugLoc dl = MI->getDebugLoc();
20766   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20767   // Address into RAX/EAX, other two args into ECX, EDX.
20768   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20769   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20770   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20771   for (int i = 0; i < X86::AddrNumOperands; ++i)
20772     MIB.addOperand(MI->getOperand(i));
20773
20774   unsigned ValOps = X86::AddrNumOperands;
20775   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20776     .addReg(MI->getOperand(ValOps).getReg());
20777   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20778     .addReg(MI->getOperand(ValOps+1).getReg());
20779
20780   // The instruction doesn't actually take any operands though.
20781   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20782
20783   MI->eraseFromParent(); // The pseudo is gone now.
20784   return BB;
20785 }
20786
20787 MachineBasicBlock *
20788 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20789                                                  MachineBasicBlock *MBB) const {
20790   // Emit va_arg instruction on X86-64.
20791
20792   // Operands to this pseudo-instruction:
20793   // 0  ) Output        : destination address (reg)
20794   // 1-5) Input         : va_list address (addr, i64mem)
20795   // 6  ) ArgSize       : Size (in bytes) of vararg type
20796   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20797   // 8  ) Align         : Alignment of type
20798   // 9  ) EFLAGS (implicit-def)
20799
20800   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20801   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
20802
20803   unsigned DestReg = MI->getOperand(0).getReg();
20804   MachineOperand &Base = MI->getOperand(1);
20805   MachineOperand &Scale = MI->getOperand(2);
20806   MachineOperand &Index = MI->getOperand(3);
20807   MachineOperand &Disp = MI->getOperand(4);
20808   MachineOperand &Segment = MI->getOperand(5);
20809   unsigned ArgSize = MI->getOperand(6).getImm();
20810   unsigned ArgMode = MI->getOperand(7).getImm();
20811   unsigned Align = MI->getOperand(8).getImm();
20812
20813   // Memory Reference
20814   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20815   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20816   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20817
20818   // Machine Information
20819   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20820   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20821   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20822   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20823   DebugLoc DL = MI->getDebugLoc();
20824
20825   // struct va_list {
20826   //   i32   gp_offset
20827   //   i32   fp_offset
20828   //   i64   overflow_area (address)
20829   //   i64   reg_save_area (address)
20830   // }
20831   // sizeof(va_list) = 24
20832   // alignment(va_list) = 8
20833
20834   unsigned TotalNumIntRegs = 6;
20835   unsigned TotalNumXMMRegs = 8;
20836   bool UseGPOffset = (ArgMode == 1);
20837   bool UseFPOffset = (ArgMode == 2);
20838   unsigned MaxOffset = TotalNumIntRegs * 8 +
20839                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20840
20841   /* Align ArgSize to a multiple of 8 */
20842   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20843   bool NeedsAlign = (Align > 8);
20844
20845   MachineBasicBlock *thisMBB = MBB;
20846   MachineBasicBlock *overflowMBB;
20847   MachineBasicBlock *offsetMBB;
20848   MachineBasicBlock *endMBB;
20849
20850   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20851   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20852   unsigned OffsetReg = 0;
20853
20854   if (!UseGPOffset && !UseFPOffset) {
20855     // If we only pull from the overflow region, we don't create a branch.
20856     // We don't need to alter control flow.
20857     OffsetDestReg = 0; // unused
20858     OverflowDestReg = DestReg;
20859
20860     offsetMBB = nullptr;
20861     overflowMBB = thisMBB;
20862     endMBB = thisMBB;
20863   } else {
20864     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20865     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20866     // If not, pull from overflow_area. (branch to overflowMBB)
20867     //
20868     //       thisMBB
20869     //         |     .
20870     //         |        .
20871     //     offsetMBB   overflowMBB
20872     //         |        .
20873     //         |     .
20874     //        endMBB
20875
20876     // Registers for the PHI in endMBB
20877     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20878     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20879
20880     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20881     MachineFunction *MF = MBB->getParent();
20882     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20883     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20884     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20885
20886     MachineFunction::iterator MBBIter = MBB;
20887     ++MBBIter;
20888
20889     // Insert the new basic blocks
20890     MF->insert(MBBIter, offsetMBB);
20891     MF->insert(MBBIter, overflowMBB);
20892     MF->insert(MBBIter, endMBB);
20893
20894     // Transfer the remainder of MBB and its successor edges to endMBB.
20895     endMBB->splice(endMBB->begin(), thisMBB,
20896                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20897     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20898
20899     // Make offsetMBB and overflowMBB successors of thisMBB
20900     thisMBB->addSuccessor(offsetMBB);
20901     thisMBB->addSuccessor(overflowMBB);
20902
20903     // endMBB is a successor of both offsetMBB and overflowMBB
20904     offsetMBB->addSuccessor(endMBB);
20905     overflowMBB->addSuccessor(endMBB);
20906
20907     // Load the offset value into a register
20908     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20909     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20910       .addOperand(Base)
20911       .addOperand(Scale)
20912       .addOperand(Index)
20913       .addDisp(Disp, UseFPOffset ? 4 : 0)
20914       .addOperand(Segment)
20915       .setMemRefs(MMOBegin, MMOEnd);
20916
20917     // Check if there is enough room left to pull this argument.
20918     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20919       .addReg(OffsetReg)
20920       .addImm(MaxOffset + 8 - ArgSizeA8);
20921
20922     // Branch to "overflowMBB" if offset >= max
20923     // Fall through to "offsetMBB" otherwise
20924     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20925       .addMBB(overflowMBB);
20926   }
20927
20928   // In offsetMBB, emit code to use the reg_save_area.
20929   if (offsetMBB) {
20930     assert(OffsetReg != 0);
20931
20932     // Read the reg_save_area address.
20933     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20934     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20935       .addOperand(Base)
20936       .addOperand(Scale)
20937       .addOperand(Index)
20938       .addDisp(Disp, 16)
20939       .addOperand(Segment)
20940       .setMemRefs(MMOBegin, MMOEnd);
20941
20942     // Zero-extend the offset
20943     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20944       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20945         .addImm(0)
20946         .addReg(OffsetReg)
20947         .addImm(X86::sub_32bit);
20948
20949     // Add the offset to the reg_save_area to get the final address.
20950     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20951       .addReg(OffsetReg64)
20952       .addReg(RegSaveReg);
20953
20954     // Compute the offset for the next argument
20955     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20956     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20957       .addReg(OffsetReg)
20958       .addImm(UseFPOffset ? 16 : 8);
20959
20960     // Store it back into the va_list.
20961     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20962       .addOperand(Base)
20963       .addOperand(Scale)
20964       .addOperand(Index)
20965       .addDisp(Disp, UseFPOffset ? 4 : 0)
20966       .addOperand(Segment)
20967       .addReg(NextOffsetReg)
20968       .setMemRefs(MMOBegin, MMOEnd);
20969
20970     // Jump to endMBB
20971     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20972       .addMBB(endMBB);
20973   }
20974
20975   //
20976   // Emit code to use overflow area
20977   //
20978
20979   // Load the overflow_area address into a register.
20980   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20981   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20982     .addOperand(Base)
20983     .addOperand(Scale)
20984     .addOperand(Index)
20985     .addDisp(Disp, 8)
20986     .addOperand(Segment)
20987     .setMemRefs(MMOBegin, MMOEnd);
20988
20989   // If we need to align it, do so. Otherwise, just copy the address
20990   // to OverflowDestReg.
20991   if (NeedsAlign) {
20992     // Align the overflow address
20993     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20994     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20995
20996     // aligned_addr = (addr + (align-1)) & ~(align-1)
20997     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20998       .addReg(OverflowAddrReg)
20999       .addImm(Align-1);
21000
21001     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21002       .addReg(TmpReg)
21003       .addImm(~(uint64_t)(Align-1));
21004   } else {
21005     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21006       .addReg(OverflowAddrReg);
21007   }
21008
21009   // Compute the next overflow address after this argument.
21010   // (the overflow address should be kept 8-byte aligned)
21011   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21012   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21013     .addReg(OverflowDestReg)
21014     .addImm(ArgSizeA8);
21015
21016   // Store the new overflow address.
21017   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21018     .addOperand(Base)
21019     .addOperand(Scale)
21020     .addOperand(Index)
21021     .addDisp(Disp, 8)
21022     .addOperand(Segment)
21023     .addReg(NextAddrReg)
21024     .setMemRefs(MMOBegin, MMOEnd);
21025
21026   // If we branched, emit the PHI to the front of endMBB.
21027   if (offsetMBB) {
21028     BuildMI(*endMBB, endMBB->begin(), DL,
21029             TII->get(X86::PHI), DestReg)
21030       .addReg(OffsetDestReg).addMBB(offsetMBB)
21031       .addReg(OverflowDestReg).addMBB(overflowMBB);
21032   }
21033
21034   // Erase the pseudo instruction
21035   MI->eraseFromParent();
21036
21037   return endMBB;
21038 }
21039
21040 MachineBasicBlock *
21041 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21042                                                  MachineInstr *MI,
21043                                                  MachineBasicBlock *MBB) const {
21044   // Emit code to save XMM registers to the stack. The ABI says that the
21045   // number of registers to save is given in %al, so it's theoretically
21046   // possible to do an indirect jump trick to avoid saving all of them,
21047   // however this code takes a simpler approach and just executes all
21048   // of the stores if %al is non-zero. It's less code, and it's probably
21049   // easier on the hardware branch predictor, and stores aren't all that
21050   // expensive anyway.
21051
21052   // Create the new basic blocks. One block contains all the XMM stores,
21053   // and one block is the final destination regardless of whether any
21054   // stores were performed.
21055   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21056   MachineFunction *F = MBB->getParent();
21057   MachineFunction::iterator MBBIter = MBB;
21058   ++MBBIter;
21059   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21060   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21061   F->insert(MBBIter, XMMSaveMBB);
21062   F->insert(MBBIter, EndMBB);
21063
21064   // Transfer the remainder of MBB and its successor edges to EndMBB.
21065   EndMBB->splice(EndMBB->begin(), MBB,
21066                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21067   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21068
21069   // The original block will now fall through to the XMM save block.
21070   MBB->addSuccessor(XMMSaveMBB);
21071   // The XMMSaveMBB will fall through to the end block.
21072   XMMSaveMBB->addSuccessor(EndMBB);
21073
21074   // Now add the instructions.
21075   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21076   DebugLoc DL = MI->getDebugLoc();
21077
21078   unsigned CountReg = MI->getOperand(0).getReg();
21079   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21080   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21081
21082   if (!Subtarget->isTargetWin64()) {
21083     // If %al is 0, branch around the XMM save block.
21084     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21085     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21086     MBB->addSuccessor(EndMBB);
21087   }
21088
21089   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21090   // that was just emitted, but clearly shouldn't be "saved".
21091   assert((MI->getNumOperands() <= 3 ||
21092           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21093           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21094          && "Expected last argument to be EFLAGS");
21095   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21096   // In the XMM save block, save all the XMM argument registers.
21097   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21098     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21099     MachineMemOperand *MMO =
21100       F->getMachineMemOperand(
21101           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
21102         MachineMemOperand::MOStore,
21103         /*Size=*/16, /*Align=*/16);
21104     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21105       .addFrameIndex(RegSaveFrameIndex)
21106       .addImm(/*Scale=*/1)
21107       .addReg(/*IndexReg=*/0)
21108       .addImm(/*Disp=*/Offset)
21109       .addReg(/*Segment=*/0)
21110       .addReg(MI->getOperand(i).getReg())
21111       .addMemOperand(MMO);
21112   }
21113
21114   MI->eraseFromParent();   // The pseudo instruction is gone now.
21115
21116   return EndMBB;
21117 }
21118
21119 // The EFLAGS operand of SelectItr might be missing a kill marker
21120 // because there were multiple uses of EFLAGS, and ISel didn't know
21121 // which to mark. Figure out whether SelectItr should have had a
21122 // kill marker, and set it if it should. Returns the correct kill
21123 // marker value.
21124 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21125                                      MachineBasicBlock* BB,
21126                                      const TargetRegisterInfo* TRI) {
21127   // Scan forward through BB for a use/def of EFLAGS.
21128   MachineBasicBlock::iterator miI(std::next(SelectItr));
21129   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21130     const MachineInstr& mi = *miI;
21131     if (mi.readsRegister(X86::EFLAGS))
21132       return false;
21133     if (mi.definesRegister(X86::EFLAGS))
21134       break; // Should have kill-flag - update below.
21135   }
21136
21137   // If we hit the end of the block, check whether EFLAGS is live into a
21138   // successor.
21139   if (miI == BB->end()) {
21140     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21141                                           sEnd = BB->succ_end();
21142          sItr != sEnd; ++sItr) {
21143       MachineBasicBlock* succ = *sItr;
21144       if (succ->isLiveIn(X86::EFLAGS))
21145         return false;
21146     }
21147   }
21148
21149   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21150   // out. SelectMI should have a kill flag on EFLAGS.
21151   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21152   return true;
21153 }
21154
21155 MachineBasicBlock *
21156 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21157                                      MachineBasicBlock *BB) const {
21158   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21159   DebugLoc DL = MI->getDebugLoc();
21160
21161   // To "insert" a SELECT_CC instruction, we actually have to insert the
21162   // diamond control-flow pattern.  The incoming instruction knows the
21163   // destination vreg to set, the condition code register to branch on, the
21164   // true/false values to select between, and a branch opcode to use.
21165   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21166   MachineFunction::iterator It = BB;
21167   ++It;
21168
21169   //  thisMBB:
21170   //  ...
21171   //   TrueVal = ...
21172   //   cmpTY ccX, r1, r2
21173   //   bCC copy1MBB
21174   //   fallthrough --> copy0MBB
21175   MachineBasicBlock *thisMBB = BB;
21176   MachineFunction *F = BB->getParent();
21177   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21178   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21179   F->insert(It, copy0MBB);
21180   F->insert(It, sinkMBB);
21181
21182   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21183   // live into the sink and copy blocks.
21184   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21185   if (!MI->killsRegister(X86::EFLAGS) &&
21186       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
21187     copy0MBB->addLiveIn(X86::EFLAGS);
21188     sinkMBB->addLiveIn(X86::EFLAGS);
21189   }
21190
21191   // Transfer the remainder of BB and its successor edges to sinkMBB.
21192   sinkMBB->splice(sinkMBB->begin(), BB,
21193                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
21194   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21195
21196   // Add the true and fallthrough blocks as its successors.
21197   BB->addSuccessor(copy0MBB);
21198   BB->addSuccessor(sinkMBB);
21199
21200   // Create the conditional branch instruction.
21201   unsigned Opc =
21202     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
21203   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21204
21205   //  copy0MBB:
21206   //   %FalseValue = ...
21207   //   # fallthrough to sinkMBB
21208   copy0MBB->addSuccessor(sinkMBB);
21209
21210   //  sinkMBB:
21211   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21212   //  ...
21213   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21214           TII->get(X86::PHI), MI->getOperand(0).getReg())
21215     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
21216     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
21217
21218   MI->eraseFromParent();   // The pseudo instruction is gone now.
21219   return sinkMBB;
21220 }
21221
21222 MachineBasicBlock *
21223 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21224                                         MachineBasicBlock *BB) const {
21225   MachineFunction *MF = BB->getParent();
21226   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21227   DebugLoc DL = MI->getDebugLoc();
21228   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21229
21230   assert(MF->shouldSplitStack());
21231
21232   const bool Is64Bit = Subtarget->is64Bit();
21233   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21234
21235   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21236   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21237
21238   // BB:
21239   //  ... [Till the alloca]
21240   // If stacklet is not large enough, jump to mallocMBB
21241   //
21242   // bumpMBB:
21243   //  Allocate by subtracting from RSP
21244   //  Jump to continueMBB
21245   //
21246   // mallocMBB:
21247   //  Allocate by call to runtime
21248   //
21249   // continueMBB:
21250   //  ...
21251   //  [rest of original BB]
21252   //
21253
21254   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21255   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21256   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21257
21258   MachineRegisterInfo &MRI = MF->getRegInfo();
21259   const TargetRegisterClass *AddrRegClass =
21260     getRegClassFor(getPointerTy());
21261
21262   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21263     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21264     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21265     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21266     sizeVReg = MI->getOperand(1).getReg(),
21267     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21268
21269   MachineFunction::iterator MBBIter = BB;
21270   ++MBBIter;
21271
21272   MF->insert(MBBIter, bumpMBB);
21273   MF->insert(MBBIter, mallocMBB);
21274   MF->insert(MBBIter, continueMBB);
21275
21276   continueMBB->splice(continueMBB->begin(), BB,
21277                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21278   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21279
21280   // Add code to the main basic block to check if the stack limit has been hit,
21281   // and if so, jump to mallocMBB otherwise to bumpMBB.
21282   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21283   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21284     .addReg(tmpSPVReg).addReg(sizeVReg);
21285   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21286     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21287     .addReg(SPLimitVReg);
21288   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21289
21290   // bumpMBB simply decreases the stack pointer, since we know the current
21291   // stacklet has enough space.
21292   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21293     .addReg(SPLimitVReg);
21294   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21295     .addReg(SPLimitVReg);
21296   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21297
21298   // Calls into a routine in libgcc to allocate more space from the heap.
21299   const uint32_t *RegMask =
21300       Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
21301   if (IsLP64) {
21302     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21303       .addReg(sizeVReg);
21304     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21305       .addExternalSymbol("__morestack_allocate_stack_space")
21306       .addRegMask(RegMask)
21307       .addReg(X86::RDI, RegState::Implicit)
21308       .addReg(X86::RAX, RegState::ImplicitDefine);
21309   } else if (Is64Bit) {
21310     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21311       .addReg(sizeVReg);
21312     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21313       .addExternalSymbol("__morestack_allocate_stack_space")
21314       .addRegMask(RegMask)
21315       .addReg(X86::EDI, RegState::Implicit)
21316       .addReg(X86::EAX, RegState::ImplicitDefine);
21317   } else {
21318     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21319       .addImm(12);
21320     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21321     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21322       .addExternalSymbol("__morestack_allocate_stack_space")
21323       .addRegMask(RegMask)
21324       .addReg(X86::EAX, RegState::ImplicitDefine);
21325   }
21326
21327   if (!Is64Bit)
21328     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21329       .addImm(16);
21330
21331   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21332     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21333   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21334
21335   // Set up the CFG correctly.
21336   BB->addSuccessor(bumpMBB);
21337   BB->addSuccessor(mallocMBB);
21338   mallocMBB->addSuccessor(continueMBB);
21339   bumpMBB->addSuccessor(continueMBB);
21340
21341   // Take care of the PHI nodes.
21342   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21343           MI->getOperand(0).getReg())
21344     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21345     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21346
21347   // Delete the original pseudo instruction.
21348   MI->eraseFromParent();
21349
21350   // And we're done.
21351   return continueMBB;
21352 }
21353
21354 MachineBasicBlock *
21355 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21356                                         MachineBasicBlock *BB) const {
21357   DebugLoc DL = MI->getDebugLoc();
21358
21359   assert(!Subtarget->isTargetMachO());
21360
21361   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
21362
21363   MI->eraseFromParent();   // The pseudo instruction is gone now.
21364   return BB;
21365 }
21366
21367 MachineBasicBlock *
21368 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21369                                       MachineBasicBlock *BB) const {
21370   // This is pretty easy.  We're taking the value that we received from
21371   // our load from the relocation, sticking it in either RDI (x86-64)
21372   // or EAX and doing an indirect call.  The return value will then
21373   // be in the normal return register.
21374   MachineFunction *F = BB->getParent();
21375   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21376   DebugLoc DL = MI->getDebugLoc();
21377
21378   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21379   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21380
21381   // Get a register mask for the lowered call.
21382   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21383   // proper register mask.
21384   const uint32_t *RegMask =
21385       Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
21386   if (Subtarget->is64Bit()) {
21387     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21388                                       TII->get(X86::MOV64rm), X86::RDI)
21389     .addReg(X86::RIP)
21390     .addImm(0).addReg(0)
21391     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21392                       MI->getOperand(3).getTargetFlags())
21393     .addReg(0);
21394     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21395     addDirectMem(MIB, X86::RDI);
21396     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21397   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21398     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21399                                       TII->get(X86::MOV32rm), X86::EAX)
21400     .addReg(0)
21401     .addImm(0).addReg(0)
21402     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21403                       MI->getOperand(3).getTargetFlags())
21404     .addReg(0);
21405     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21406     addDirectMem(MIB, X86::EAX);
21407     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21408   } else {
21409     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21410                                       TII->get(X86::MOV32rm), X86::EAX)
21411     .addReg(TII->getGlobalBaseReg(F))
21412     .addImm(0).addReg(0)
21413     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21414                       MI->getOperand(3).getTargetFlags())
21415     .addReg(0);
21416     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21417     addDirectMem(MIB, X86::EAX);
21418     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21419   }
21420
21421   MI->eraseFromParent(); // The pseudo instruction is gone now.
21422   return BB;
21423 }
21424
21425 MachineBasicBlock *
21426 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21427                                     MachineBasicBlock *MBB) const {
21428   DebugLoc DL = MI->getDebugLoc();
21429   MachineFunction *MF = MBB->getParent();
21430   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21431   MachineRegisterInfo &MRI = MF->getRegInfo();
21432
21433   const BasicBlock *BB = MBB->getBasicBlock();
21434   MachineFunction::iterator I = MBB;
21435   ++I;
21436
21437   // Memory Reference
21438   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21439   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21440
21441   unsigned DstReg;
21442   unsigned MemOpndSlot = 0;
21443
21444   unsigned CurOp = 0;
21445
21446   DstReg = MI->getOperand(CurOp++).getReg();
21447   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21448   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21449   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21450   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21451
21452   MemOpndSlot = CurOp;
21453
21454   MVT PVT = getPointerTy();
21455   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21456          "Invalid Pointer Size!");
21457
21458   // For v = setjmp(buf), we generate
21459   //
21460   // thisMBB:
21461   //  buf[LabelOffset] = restoreMBB
21462   //  SjLjSetup restoreMBB
21463   //
21464   // mainMBB:
21465   //  v_main = 0
21466   //
21467   // sinkMBB:
21468   //  v = phi(main, restore)
21469   //
21470   // restoreMBB:
21471   //  if base pointer being used, load it from frame
21472   //  v_restore = 1
21473
21474   MachineBasicBlock *thisMBB = MBB;
21475   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21476   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21477   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21478   MF->insert(I, mainMBB);
21479   MF->insert(I, sinkMBB);
21480   MF->push_back(restoreMBB);
21481
21482   MachineInstrBuilder MIB;
21483
21484   // Transfer the remainder of BB and its successor edges to sinkMBB.
21485   sinkMBB->splice(sinkMBB->begin(), MBB,
21486                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21487   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21488
21489   // thisMBB:
21490   unsigned PtrStoreOpc = 0;
21491   unsigned LabelReg = 0;
21492   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21493   Reloc::Model RM = MF->getTarget().getRelocationModel();
21494   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21495                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21496
21497   // Prepare IP either in reg or imm.
21498   if (!UseImmLabel) {
21499     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21500     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21501     LabelReg = MRI.createVirtualRegister(PtrRC);
21502     if (Subtarget->is64Bit()) {
21503       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21504               .addReg(X86::RIP)
21505               .addImm(0)
21506               .addReg(0)
21507               .addMBB(restoreMBB)
21508               .addReg(0);
21509     } else {
21510       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21511       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21512               .addReg(XII->getGlobalBaseReg(MF))
21513               .addImm(0)
21514               .addReg(0)
21515               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21516               .addReg(0);
21517     }
21518   } else
21519     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21520   // Store IP
21521   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21522   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21523     if (i == X86::AddrDisp)
21524       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21525     else
21526       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21527   }
21528   if (!UseImmLabel)
21529     MIB.addReg(LabelReg);
21530   else
21531     MIB.addMBB(restoreMBB);
21532   MIB.setMemRefs(MMOBegin, MMOEnd);
21533   // Setup
21534   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21535           .addMBB(restoreMBB);
21536
21537   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21538   MIB.addRegMask(RegInfo->getNoPreservedMask());
21539   thisMBB->addSuccessor(mainMBB);
21540   thisMBB->addSuccessor(restoreMBB);
21541
21542   // mainMBB:
21543   //  EAX = 0
21544   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21545   mainMBB->addSuccessor(sinkMBB);
21546
21547   // sinkMBB:
21548   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21549           TII->get(X86::PHI), DstReg)
21550     .addReg(mainDstReg).addMBB(mainMBB)
21551     .addReg(restoreDstReg).addMBB(restoreMBB);
21552
21553   // restoreMBB:
21554   if (RegInfo->hasBasePointer(*MF)) {
21555     const bool Uses64BitFramePtr =
21556         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21557     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21558     X86FI->setRestoreBasePointer(MF);
21559     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21560     unsigned BasePtr = RegInfo->getBaseRegister();
21561     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21562     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21563                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21564       .setMIFlag(MachineInstr::FrameSetup);
21565   }
21566   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21567   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21568   restoreMBB->addSuccessor(sinkMBB);
21569
21570   MI->eraseFromParent();
21571   return sinkMBB;
21572 }
21573
21574 MachineBasicBlock *
21575 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21576                                      MachineBasicBlock *MBB) const {
21577   DebugLoc DL = MI->getDebugLoc();
21578   MachineFunction *MF = MBB->getParent();
21579   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21580   MachineRegisterInfo &MRI = MF->getRegInfo();
21581
21582   // Memory Reference
21583   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21584   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21585
21586   MVT PVT = getPointerTy();
21587   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21588          "Invalid Pointer Size!");
21589
21590   const TargetRegisterClass *RC =
21591     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21592   unsigned Tmp = MRI.createVirtualRegister(RC);
21593   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21594   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21595   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21596   unsigned SP = RegInfo->getStackRegister();
21597
21598   MachineInstrBuilder MIB;
21599
21600   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21601   const int64_t SPOffset = 2 * PVT.getStoreSize();
21602
21603   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21604   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21605
21606   // Reload FP
21607   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21608   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21609     MIB.addOperand(MI->getOperand(i));
21610   MIB.setMemRefs(MMOBegin, MMOEnd);
21611   // Reload IP
21612   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21613   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21614     if (i == X86::AddrDisp)
21615       MIB.addDisp(MI->getOperand(i), LabelOffset);
21616     else
21617       MIB.addOperand(MI->getOperand(i));
21618   }
21619   MIB.setMemRefs(MMOBegin, MMOEnd);
21620   // Reload SP
21621   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21622   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21623     if (i == X86::AddrDisp)
21624       MIB.addDisp(MI->getOperand(i), SPOffset);
21625     else
21626       MIB.addOperand(MI->getOperand(i));
21627   }
21628   MIB.setMemRefs(MMOBegin, MMOEnd);
21629   // Jump
21630   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21631
21632   MI->eraseFromParent();
21633   return MBB;
21634 }
21635
21636 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21637 // accumulator loops. Writing back to the accumulator allows the coalescer
21638 // to remove extra copies in the loop.
21639 MachineBasicBlock *
21640 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21641                                  MachineBasicBlock *MBB) const {
21642   MachineOperand &AddendOp = MI->getOperand(3);
21643
21644   // Bail out early if the addend isn't a register - we can't switch these.
21645   if (!AddendOp.isReg())
21646     return MBB;
21647
21648   MachineFunction &MF = *MBB->getParent();
21649   MachineRegisterInfo &MRI = MF.getRegInfo();
21650
21651   // Check whether the addend is defined by a PHI:
21652   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21653   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21654   if (!AddendDef.isPHI())
21655     return MBB;
21656
21657   // Look for the following pattern:
21658   // loop:
21659   //   %addend = phi [%entry, 0], [%loop, %result]
21660   //   ...
21661   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21662
21663   // Replace with:
21664   //   loop:
21665   //   %addend = phi [%entry, 0], [%loop, %result]
21666   //   ...
21667   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21668
21669   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21670     assert(AddendDef.getOperand(i).isReg());
21671     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21672     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21673     if (&PHISrcInst == MI) {
21674       // Found a matching instruction.
21675       unsigned NewFMAOpc = 0;
21676       switch (MI->getOpcode()) {
21677         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21678         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21679         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21680         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21681         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21682         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21683         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21684         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21685         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21686         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21687         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21688         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21689         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21690         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21691         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21692         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21693         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21694         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21695         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21696         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21697
21698         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21699         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21700         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21701         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21702         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21703         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21704         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21705         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21706         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21707         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21708         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21709         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21710         default: llvm_unreachable("Unrecognized FMA variant.");
21711       }
21712
21713       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21714       MachineInstrBuilder MIB =
21715         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21716         .addOperand(MI->getOperand(0))
21717         .addOperand(MI->getOperand(3))
21718         .addOperand(MI->getOperand(2))
21719         .addOperand(MI->getOperand(1));
21720       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21721       MI->eraseFromParent();
21722     }
21723   }
21724
21725   return MBB;
21726 }
21727
21728 MachineBasicBlock *
21729 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21730                                                MachineBasicBlock *BB) const {
21731   switch (MI->getOpcode()) {
21732   default: llvm_unreachable("Unexpected instr type to insert");
21733   case X86::TAILJMPd64:
21734   case X86::TAILJMPr64:
21735   case X86::TAILJMPm64:
21736   case X86::TAILJMPd64_REX:
21737   case X86::TAILJMPr64_REX:
21738   case X86::TAILJMPm64_REX:
21739     llvm_unreachable("TAILJMP64 would not be touched here.");
21740   case X86::TCRETURNdi64:
21741   case X86::TCRETURNri64:
21742   case X86::TCRETURNmi64:
21743     return BB;
21744   case X86::WIN_ALLOCA:
21745     return EmitLoweredWinAlloca(MI, BB);
21746   case X86::SEG_ALLOCA_32:
21747   case X86::SEG_ALLOCA_64:
21748     return EmitLoweredSegAlloca(MI, BB);
21749   case X86::TLSCall_32:
21750   case X86::TLSCall_64:
21751     return EmitLoweredTLSCall(MI, BB);
21752   case X86::CMOV_GR8:
21753   case X86::CMOV_FR32:
21754   case X86::CMOV_FR64:
21755   case X86::CMOV_V4F32:
21756   case X86::CMOV_V2F64:
21757   case X86::CMOV_V2I64:
21758   case X86::CMOV_V8F32:
21759   case X86::CMOV_V4F64:
21760   case X86::CMOV_V4I64:
21761   case X86::CMOV_V16F32:
21762   case X86::CMOV_V8F64:
21763   case X86::CMOV_V8I64:
21764   case X86::CMOV_GR16:
21765   case X86::CMOV_GR32:
21766   case X86::CMOV_RFP32:
21767   case X86::CMOV_RFP64:
21768   case X86::CMOV_RFP80:
21769     return EmitLoweredSelect(MI, BB);
21770
21771   case X86::FP32_TO_INT16_IN_MEM:
21772   case X86::FP32_TO_INT32_IN_MEM:
21773   case X86::FP32_TO_INT64_IN_MEM:
21774   case X86::FP64_TO_INT16_IN_MEM:
21775   case X86::FP64_TO_INT32_IN_MEM:
21776   case X86::FP64_TO_INT64_IN_MEM:
21777   case X86::FP80_TO_INT16_IN_MEM:
21778   case X86::FP80_TO_INT32_IN_MEM:
21779   case X86::FP80_TO_INT64_IN_MEM: {
21780     MachineFunction *F = BB->getParent();
21781     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21782     DebugLoc DL = MI->getDebugLoc();
21783
21784     // Change the floating point control register to use "round towards zero"
21785     // mode when truncating to an integer value.
21786     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21787     addFrameReference(BuildMI(*BB, MI, DL,
21788                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21789
21790     // Load the old value of the high byte of the control word...
21791     unsigned OldCW =
21792       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21793     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21794                       CWFrameIdx);
21795
21796     // Set the high part to be round to zero...
21797     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21798       .addImm(0xC7F);
21799
21800     // Reload the modified control word now...
21801     addFrameReference(BuildMI(*BB, MI, DL,
21802                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21803
21804     // Restore the memory image of control word to original value
21805     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21806       .addReg(OldCW);
21807
21808     // Get the X86 opcode to use.
21809     unsigned Opc;
21810     switch (MI->getOpcode()) {
21811     default: llvm_unreachable("illegal opcode!");
21812     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21813     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21814     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21815     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21816     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21817     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21818     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21819     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21820     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21821     }
21822
21823     X86AddressMode AM;
21824     MachineOperand &Op = MI->getOperand(0);
21825     if (Op.isReg()) {
21826       AM.BaseType = X86AddressMode::RegBase;
21827       AM.Base.Reg = Op.getReg();
21828     } else {
21829       AM.BaseType = X86AddressMode::FrameIndexBase;
21830       AM.Base.FrameIndex = Op.getIndex();
21831     }
21832     Op = MI->getOperand(1);
21833     if (Op.isImm())
21834       AM.Scale = Op.getImm();
21835     Op = MI->getOperand(2);
21836     if (Op.isImm())
21837       AM.IndexReg = Op.getImm();
21838     Op = MI->getOperand(3);
21839     if (Op.isGlobal()) {
21840       AM.GV = Op.getGlobal();
21841     } else {
21842       AM.Disp = Op.getImm();
21843     }
21844     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21845                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21846
21847     // Reload the original control word now.
21848     addFrameReference(BuildMI(*BB, MI, DL,
21849                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21850
21851     MI->eraseFromParent();   // The pseudo instruction is gone now.
21852     return BB;
21853   }
21854     // String/text processing lowering.
21855   case X86::PCMPISTRM128REG:
21856   case X86::VPCMPISTRM128REG:
21857   case X86::PCMPISTRM128MEM:
21858   case X86::VPCMPISTRM128MEM:
21859   case X86::PCMPESTRM128REG:
21860   case X86::VPCMPESTRM128REG:
21861   case X86::PCMPESTRM128MEM:
21862   case X86::VPCMPESTRM128MEM:
21863     assert(Subtarget->hasSSE42() &&
21864            "Target must have SSE4.2 or AVX features enabled");
21865     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21866
21867   // String/text processing lowering.
21868   case X86::PCMPISTRIREG:
21869   case X86::VPCMPISTRIREG:
21870   case X86::PCMPISTRIMEM:
21871   case X86::VPCMPISTRIMEM:
21872   case X86::PCMPESTRIREG:
21873   case X86::VPCMPESTRIREG:
21874   case X86::PCMPESTRIMEM:
21875   case X86::VPCMPESTRIMEM:
21876     assert(Subtarget->hasSSE42() &&
21877            "Target must have SSE4.2 or AVX features enabled");
21878     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21879
21880   // Thread synchronization.
21881   case X86::MONITOR:
21882     return EmitMonitor(MI, BB, Subtarget);
21883
21884   // xbegin
21885   case X86::XBEGIN:
21886     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21887
21888   case X86::VASTART_SAVE_XMM_REGS:
21889     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21890
21891   case X86::VAARG_64:
21892     return EmitVAARG64WithCustomInserter(MI, BB);
21893
21894   case X86::EH_SjLj_SetJmp32:
21895   case X86::EH_SjLj_SetJmp64:
21896     return emitEHSjLjSetJmp(MI, BB);
21897
21898   case X86::EH_SjLj_LongJmp32:
21899   case X86::EH_SjLj_LongJmp64:
21900     return emitEHSjLjLongJmp(MI, BB);
21901
21902   case TargetOpcode::STATEPOINT:
21903     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21904     // this point in the process.  We diverge later.
21905     return emitPatchPoint(MI, BB);
21906
21907   case TargetOpcode::STACKMAP:
21908   case TargetOpcode::PATCHPOINT:
21909     return emitPatchPoint(MI, BB);
21910
21911   case X86::VFMADDPDr213r:
21912   case X86::VFMADDPSr213r:
21913   case X86::VFMADDSDr213r:
21914   case X86::VFMADDSSr213r:
21915   case X86::VFMSUBPDr213r:
21916   case X86::VFMSUBPSr213r:
21917   case X86::VFMSUBSDr213r:
21918   case X86::VFMSUBSSr213r:
21919   case X86::VFNMADDPDr213r:
21920   case X86::VFNMADDPSr213r:
21921   case X86::VFNMADDSDr213r:
21922   case X86::VFNMADDSSr213r:
21923   case X86::VFNMSUBPDr213r:
21924   case X86::VFNMSUBPSr213r:
21925   case X86::VFNMSUBSDr213r:
21926   case X86::VFNMSUBSSr213r:
21927   case X86::VFMADDSUBPDr213r:
21928   case X86::VFMADDSUBPSr213r:
21929   case X86::VFMSUBADDPDr213r:
21930   case X86::VFMSUBADDPSr213r:
21931   case X86::VFMADDPDr213rY:
21932   case X86::VFMADDPSr213rY:
21933   case X86::VFMSUBPDr213rY:
21934   case X86::VFMSUBPSr213rY:
21935   case X86::VFNMADDPDr213rY:
21936   case X86::VFNMADDPSr213rY:
21937   case X86::VFNMSUBPDr213rY:
21938   case X86::VFNMSUBPSr213rY:
21939   case X86::VFMADDSUBPDr213rY:
21940   case X86::VFMADDSUBPSr213rY:
21941   case X86::VFMSUBADDPDr213rY:
21942   case X86::VFMSUBADDPSr213rY:
21943     return emitFMA3Instr(MI, BB);
21944   }
21945 }
21946
21947 //===----------------------------------------------------------------------===//
21948 //                           X86 Optimization Hooks
21949 //===----------------------------------------------------------------------===//
21950
21951 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21952                                                       APInt &KnownZero,
21953                                                       APInt &KnownOne,
21954                                                       const SelectionDAG &DAG,
21955                                                       unsigned Depth) const {
21956   unsigned BitWidth = KnownZero.getBitWidth();
21957   unsigned Opc = Op.getOpcode();
21958   assert((Opc >= ISD::BUILTIN_OP_END ||
21959           Opc == ISD::INTRINSIC_WO_CHAIN ||
21960           Opc == ISD::INTRINSIC_W_CHAIN ||
21961           Opc == ISD::INTRINSIC_VOID) &&
21962          "Should use MaskedValueIsZero if you don't know whether Op"
21963          " is a target node!");
21964
21965   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21966   switch (Opc) {
21967   default: break;
21968   case X86ISD::ADD:
21969   case X86ISD::SUB:
21970   case X86ISD::ADC:
21971   case X86ISD::SBB:
21972   case X86ISD::SMUL:
21973   case X86ISD::UMUL:
21974   case X86ISD::INC:
21975   case X86ISD::DEC:
21976   case X86ISD::OR:
21977   case X86ISD::XOR:
21978   case X86ISD::AND:
21979     // These nodes' second result is a boolean.
21980     if (Op.getResNo() == 0)
21981       break;
21982     // Fallthrough
21983   case X86ISD::SETCC:
21984     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21985     break;
21986   case ISD::INTRINSIC_WO_CHAIN: {
21987     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21988     unsigned NumLoBits = 0;
21989     switch (IntId) {
21990     default: break;
21991     case Intrinsic::x86_sse_movmsk_ps:
21992     case Intrinsic::x86_avx_movmsk_ps_256:
21993     case Intrinsic::x86_sse2_movmsk_pd:
21994     case Intrinsic::x86_avx_movmsk_pd_256:
21995     case Intrinsic::x86_mmx_pmovmskb:
21996     case Intrinsic::x86_sse2_pmovmskb_128:
21997     case Intrinsic::x86_avx2_pmovmskb: {
21998       // High bits of movmskp{s|d}, pmovmskb are known zero.
21999       switch (IntId) {
22000         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22001         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22002         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22003         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22004         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22005         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22006         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22007         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22008       }
22009       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22010       break;
22011     }
22012     }
22013     break;
22014   }
22015   }
22016 }
22017
22018 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22019   SDValue Op,
22020   const SelectionDAG &,
22021   unsigned Depth) const {
22022   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22023   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22024     return Op.getValueType().getScalarType().getSizeInBits();
22025
22026   // Fallback case.
22027   return 1;
22028 }
22029
22030 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22031 /// node is a GlobalAddress + offset.
22032 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22033                                        const GlobalValue* &GA,
22034                                        int64_t &Offset) const {
22035   if (N->getOpcode() == X86ISD::Wrapper) {
22036     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22037       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22038       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22039       return true;
22040     }
22041   }
22042   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22043 }
22044
22045 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22046 /// same as extracting the high 128-bit part of 256-bit vector and then
22047 /// inserting the result into the low part of a new 256-bit vector
22048 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22049   EVT VT = SVOp->getValueType(0);
22050   unsigned NumElems = VT.getVectorNumElements();
22051
22052   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22053   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22054     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22055         SVOp->getMaskElt(j) >= 0)
22056       return false;
22057
22058   return true;
22059 }
22060
22061 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22062 /// same as extracting the low 128-bit part of 256-bit vector and then
22063 /// inserting the result into the high part of a new 256-bit vector
22064 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22065   EVT VT = SVOp->getValueType(0);
22066   unsigned NumElems = VT.getVectorNumElements();
22067
22068   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22069   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22070     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22071         SVOp->getMaskElt(j) >= 0)
22072       return false;
22073
22074   return true;
22075 }
22076
22077 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22078 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22079                                         TargetLowering::DAGCombinerInfo &DCI,
22080                                         const X86Subtarget* Subtarget) {
22081   SDLoc dl(N);
22082   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22083   SDValue V1 = SVOp->getOperand(0);
22084   SDValue V2 = SVOp->getOperand(1);
22085   EVT VT = SVOp->getValueType(0);
22086   unsigned NumElems = VT.getVectorNumElements();
22087
22088   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22089       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22090     //
22091     //                   0,0,0,...
22092     //                      |
22093     //    V      UNDEF    BUILD_VECTOR    UNDEF
22094     //     \      /           \           /
22095     //  CONCAT_VECTOR         CONCAT_VECTOR
22096     //         \                  /
22097     //          \                /
22098     //          RESULT: V + zero extended
22099     //
22100     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22101         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22102         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22103       return SDValue();
22104
22105     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22106       return SDValue();
22107
22108     // To match the shuffle mask, the first half of the mask should
22109     // be exactly the first vector, and all the rest a splat with the
22110     // first element of the second one.
22111     for (unsigned i = 0; i != NumElems/2; ++i)
22112       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22113           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22114         return SDValue();
22115
22116     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22117     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22118       if (Ld->hasNUsesOfValue(1, 0)) {
22119         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22120         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22121         SDValue ResNode =
22122           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22123                                   Ld->getMemoryVT(),
22124                                   Ld->getPointerInfo(),
22125                                   Ld->getAlignment(),
22126                                   false/*isVolatile*/, true/*ReadMem*/,
22127                                   false/*WriteMem*/);
22128
22129         // Make sure the newly-created LOAD is in the same position as Ld in
22130         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22131         // and update uses of Ld's output chain to use the TokenFactor.
22132         if (Ld->hasAnyUseOfValue(1)) {
22133           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22134                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22135           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22136           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22137                                  SDValue(ResNode.getNode(), 1));
22138         }
22139
22140         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
22141       }
22142     }
22143
22144     // Emit a zeroed vector and insert the desired subvector on its
22145     // first half.
22146     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22147     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22148     return DCI.CombineTo(N, InsV);
22149   }
22150
22151   //===--------------------------------------------------------------------===//
22152   // Combine some shuffles into subvector extracts and inserts:
22153   //
22154
22155   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22156   if (isShuffleHigh128VectorInsertLow(SVOp)) {
22157     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22158     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22159     return DCI.CombineTo(N, InsV);
22160   }
22161
22162   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22163   if (isShuffleLow128VectorInsertHigh(SVOp)) {
22164     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22165     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22166     return DCI.CombineTo(N, InsV);
22167   }
22168
22169   return SDValue();
22170 }
22171
22172 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22173 /// possible.
22174 ///
22175 /// This is the leaf of the recursive combinine below. When we have found some
22176 /// chain of single-use x86 shuffle instructions and accumulated the combined
22177 /// shuffle mask represented by them, this will try to pattern match that mask
22178 /// into either a single instruction if there is a special purpose instruction
22179 /// for this operation, or into a PSHUFB instruction which is a fully general
22180 /// instruction but should only be used to replace chains over a certain depth.
22181 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22182                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22183                                    TargetLowering::DAGCombinerInfo &DCI,
22184                                    const X86Subtarget *Subtarget) {
22185   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22186
22187   // Find the operand that enters the chain. Note that multiple uses are OK
22188   // here, we're not going to remove the operand we find.
22189   SDValue Input = Op.getOperand(0);
22190   while (Input.getOpcode() == ISD::BITCAST)
22191     Input = Input.getOperand(0);
22192
22193   MVT VT = Input.getSimpleValueType();
22194   MVT RootVT = Root.getSimpleValueType();
22195   SDLoc DL(Root);
22196
22197   // Just remove no-op shuffle masks.
22198   if (Mask.size() == 1) {
22199     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
22200                   /*AddTo*/ true);
22201     return true;
22202   }
22203
22204   // Use the float domain if the operand type is a floating point type.
22205   bool FloatDomain = VT.isFloatingPoint();
22206
22207   // For floating point shuffles, we don't have free copies in the shuffle
22208   // instructions or the ability to load as part of the instruction, so
22209   // canonicalize their shuffles to UNPCK or MOV variants.
22210   //
22211   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22212   // vectors because it can have a load folded into it that UNPCK cannot. This
22213   // doesn't preclude something switching to the shorter encoding post-RA.
22214   if (FloatDomain) {
22215     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
22216       bool Lo = Mask.equals(0, 0);
22217       unsigned Shuffle;
22218       MVT ShuffleVT;
22219       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22220       // is no slower than UNPCKLPD but has the option to fold the input operand
22221       // into even an unaligned memory load.
22222       if (Lo && Subtarget->hasSSE3()) {
22223         Shuffle = X86ISD::MOVDDUP;
22224         ShuffleVT = MVT::v2f64;
22225       } else {
22226         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22227         // than the UNPCK variants.
22228         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22229         ShuffleVT = MVT::v4f32;
22230       }
22231       if (Depth == 1 && Root->getOpcode() == Shuffle)
22232         return false; // Nothing to do!
22233       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
22234       DCI.AddToWorklist(Op.getNode());
22235       if (Shuffle == X86ISD::MOVDDUP)
22236         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22237       else
22238         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22239       DCI.AddToWorklist(Op.getNode());
22240       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
22241                     /*AddTo*/ true);
22242       return true;
22243     }
22244     if (Subtarget->hasSSE3() &&
22245         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
22246       bool Lo = Mask.equals(0, 0, 2, 2);
22247       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22248       MVT ShuffleVT = MVT::v4f32;
22249       if (Depth == 1 && Root->getOpcode() == Shuffle)
22250         return false; // Nothing to do!
22251       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
22252       DCI.AddToWorklist(Op.getNode());
22253       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22254       DCI.AddToWorklist(Op.getNode());
22255       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
22256                     /*AddTo*/ true);
22257       return true;
22258     }
22259     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
22260       bool Lo = Mask.equals(0, 0, 1, 1);
22261       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22262       MVT ShuffleVT = MVT::v4f32;
22263       if (Depth == 1 && Root->getOpcode() == Shuffle)
22264         return false; // Nothing to do!
22265       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
22266       DCI.AddToWorklist(Op.getNode());
22267       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22268       DCI.AddToWorklist(Op.getNode());
22269       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
22270                     /*AddTo*/ true);
22271       return true;
22272     }
22273   }
22274
22275   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22276   // variants as none of these have single-instruction variants that are
22277   // superior to the UNPCK formulation.
22278   if (!FloatDomain &&
22279       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
22280        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
22281        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
22282        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
22283                    15))) {
22284     bool Lo = Mask[0] == 0;
22285     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22286     if (Depth == 1 && Root->getOpcode() == Shuffle)
22287       return false; // Nothing to do!
22288     MVT ShuffleVT;
22289     switch (Mask.size()) {
22290     case 8:
22291       ShuffleVT = MVT::v8i16;
22292       break;
22293     case 16:
22294       ShuffleVT = MVT::v16i8;
22295       break;
22296     default:
22297       llvm_unreachable("Impossible mask size!");
22298     };
22299     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
22300     DCI.AddToWorklist(Op.getNode());
22301     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22302     DCI.AddToWorklist(Op.getNode());
22303     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
22304                   /*AddTo*/ true);
22305     return true;
22306   }
22307
22308   // Don't try to re-form single instruction chains under any circumstances now
22309   // that we've done encoding canonicalization for them.
22310   if (Depth < 2)
22311     return false;
22312
22313   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22314   // can replace them with a single PSHUFB instruction profitably. Intel's
22315   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22316   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22317   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22318     SmallVector<SDValue, 16> PSHUFBMask;
22319     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
22320     int Ratio = 16 / Mask.size();
22321     for (unsigned i = 0; i < 16; ++i) {
22322       if (Mask[i / Ratio] == SM_SentinelUndef) {
22323         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22324         continue;
22325       }
22326       int M = Mask[i / Ratio] != SM_SentinelZero
22327                   ? Ratio * Mask[i / Ratio] + i % Ratio
22328                   : 255;
22329       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
22330     }
22331     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
22332     DCI.AddToWorklist(Op.getNode());
22333     SDValue PSHUFBMaskOp =
22334         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
22335     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22336     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
22337     DCI.AddToWorklist(Op.getNode());
22338     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
22339                   /*AddTo*/ true);
22340     return true;
22341   }
22342
22343   // Failed to find any combines.
22344   return false;
22345 }
22346
22347 /// \brief Fully generic combining of x86 shuffle instructions.
22348 ///
22349 /// This should be the last combine run over the x86 shuffle instructions. Once
22350 /// they have been fully optimized, this will recursively consider all chains
22351 /// of single-use shuffle instructions, build a generic model of the cumulative
22352 /// shuffle operation, and check for simpler instructions which implement this
22353 /// operation. We use this primarily for two purposes:
22354 ///
22355 /// 1) Collapse generic shuffles to specialized single instructions when
22356 ///    equivalent. In most cases, this is just an encoding size win, but
22357 ///    sometimes we will collapse multiple generic shuffles into a single
22358 ///    special-purpose shuffle.
22359 /// 2) Look for sequences of shuffle instructions with 3 or more total
22360 ///    instructions, and replace them with the slightly more expensive SSSE3
22361 ///    PSHUFB instruction if available. We do this as the last combining step
22362 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22363 ///    a suitable short sequence of other instructions. The PHUFB will either
22364 ///    use a register or have to read from memory and so is slightly (but only
22365 ///    slightly) more expensive than the other shuffle instructions.
22366 ///
22367 /// Because this is inherently a quadratic operation (for each shuffle in
22368 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22369 /// This should never be an issue in practice as the shuffle lowering doesn't
22370 /// produce sequences of more than 8 instructions.
22371 ///
22372 /// FIXME: We will currently miss some cases where the redundant shuffling
22373 /// would simplify under the threshold for PSHUFB formation because of
22374 /// combine-ordering. To fix this, we should do the redundant instruction
22375 /// combining in this recursive walk.
22376 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22377                                           ArrayRef<int> RootMask,
22378                                           int Depth, bool HasPSHUFB,
22379                                           SelectionDAG &DAG,
22380                                           TargetLowering::DAGCombinerInfo &DCI,
22381                                           const X86Subtarget *Subtarget) {
22382   // Bound the depth of our recursive combine because this is ultimately
22383   // quadratic in nature.
22384   if (Depth > 8)
22385     return false;
22386
22387   // Directly rip through bitcasts to find the underlying operand.
22388   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22389     Op = Op.getOperand(0);
22390
22391   MVT VT = Op.getSimpleValueType();
22392   if (!VT.isVector())
22393     return false; // Bail if we hit a non-vector.
22394   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
22395   // version should be added.
22396   if (VT.getSizeInBits() != 128)
22397     return false;
22398
22399   assert(Root.getSimpleValueType().isVector() &&
22400          "Shuffles operate on vector types!");
22401   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22402          "Can only combine shuffles of the same vector register size.");
22403
22404   if (!isTargetShuffle(Op.getOpcode()))
22405     return false;
22406   SmallVector<int, 16> OpMask;
22407   bool IsUnary;
22408   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22409   // We only can combine unary shuffles which we can decode the mask for.
22410   if (!HaveMask || !IsUnary)
22411     return false;
22412
22413   assert(VT.getVectorNumElements() == OpMask.size() &&
22414          "Different mask size from vector size!");
22415   assert(((RootMask.size() > OpMask.size() &&
22416            RootMask.size() % OpMask.size() == 0) ||
22417           (OpMask.size() > RootMask.size() &&
22418            OpMask.size() % RootMask.size() == 0) ||
22419           OpMask.size() == RootMask.size()) &&
22420          "The smaller number of elements must divide the larger.");
22421   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22422   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22423   assert(((RootRatio == 1 && OpRatio == 1) ||
22424           (RootRatio == 1) != (OpRatio == 1)) &&
22425          "Must not have a ratio for both incoming and op masks!");
22426
22427   SmallVector<int, 16> Mask;
22428   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22429
22430   // Merge this shuffle operation's mask into our accumulated mask. Note that
22431   // this shuffle's mask will be the first applied to the input, followed by the
22432   // root mask to get us all the way to the root value arrangement. The reason
22433   // for this order is that we are recursing up the operation chain.
22434   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22435     int RootIdx = i / RootRatio;
22436     if (RootMask[RootIdx] < 0) {
22437       // This is a zero or undef lane, we're done.
22438       Mask.push_back(RootMask[RootIdx]);
22439       continue;
22440     }
22441
22442     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22443     int OpIdx = RootMaskedIdx / OpRatio;
22444     if (OpMask[OpIdx] < 0) {
22445       // The incoming lanes are zero or undef, it doesn't matter which ones we
22446       // are using.
22447       Mask.push_back(OpMask[OpIdx]);
22448       continue;
22449     }
22450
22451     // Ok, we have non-zero lanes, map them through.
22452     Mask.push_back(OpMask[OpIdx] * OpRatio +
22453                    RootMaskedIdx % OpRatio);
22454   }
22455
22456   // See if we can recurse into the operand to combine more things.
22457   switch (Op.getOpcode()) {
22458     case X86ISD::PSHUFB:
22459       HasPSHUFB = true;
22460     case X86ISD::PSHUFD:
22461     case X86ISD::PSHUFHW:
22462     case X86ISD::PSHUFLW:
22463       if (Op.getOperand(0).hasOneUse() &&
22464           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22465                                         HasPSHUFB, DAG, DCI, Subtarget))
22466         return true;
22467       break;
22468
22469     case X86ISD::UNPCKL:
22470     case X86ISD::UNPCKH:
22471       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
22472       // We can't check for single use, we have to check that this shuffle is the only user.
22473       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22474           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22475                                         HasPSHUFB, DAG, DCI, Subtarget))
22476           return true;
22477       break;
22478   }
22479
22480   // Minor canonicalization of the accumulated shuffle mask to make it easier
22481   // to match below. All this does is detect masks with squential pairs of
22482   // elements, and shrink them to the half-width mask. It does this in a loop
22483   // so it will reduce the size of the mask to the minimal width mask which
22484   // performs an equivalent shuffle.
22485   SmallVector<int, 16> WidenedMask;
22486   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22487     Mask = std::move(WidenedMask);
22488     WidenedMask.clear();
22489   }
22490
22491   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22492                                 Subtarget);
22493 }
22494
22495 /// \brief Get the PSHUF-style mask from PSHUF node.
22496 ///
22497 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22498 /// PSHUF-style masks that can be reused with such instructions.
22499 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22500   SmallVector<int, 4> Mask;
22501   bool IsUnary;
22502   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
22503   (void)HaveMask;
22504   assert(HaveMask);
22505
22506   switch (N.getOpcode()) {
22507   case X86ISD::PSHUFD:
22508     return Mask;
22509   case X86ISD::PSHUFLW:
22510     Mask.resize(4);
22511     return Mask;
22512   case X86ISD::PSHUFHW:
22513     Mask.erase(Mask.begin(), Mask.begin() + 4);
22514     for (int &M : Mask)
22515       M -= 4;
22516     return Mask;
22517   default:
22518     llvm_unreachable("No valid shuffle instruction found!");
22519   }
22520 }
22521
22522 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22523 ///
22524 /// We walk up the chain and look for a combinable shuffle, skipping over
22525 /// shuffles that we could hoist this shuffle's transformation past without
22526 /// altering anything.
22527 static SDValue
22528 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22529                              SelectionDAG &DAG,
22530                              TargetLowering::DAGCombinerInfo &DCI) {
22531   assert(N.getOpcode() == X86ISD::PSHUFD &&
22532          "Called with something other than an x86 128-bit half shuffle!");
22533   SDLoc DL(N);
22534
22535   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22536   // of the shuffles in the chain so that we can form a fresh chain to replace
22537   // this one.
22538   SmallVector<SDValue, 8> Chain;
22539   SDValue V = N.getOperand(0);
22540   for (; V.hasOneUse(); V = V.getOperand(0)) {
22541     switch (V.getOpcode()) {
22542     default:
22543       return SDValue(); // Nothing combined!
22544
22545     case ISD::BITCAST:
22546       // Skip bitcasts as we always know the type for the target specific
22547       // instructions.
22548       continue;
22549
22550     case X86ISD::PSHUFD:
22551       // Found another dword shuffle.
22552       break;
22553
22554     case X86ISD::PSHUFLW:
22555       // Check that the low words (being shuffled) are the identity in the
22556       // dword shuffle, and the high words are self-contained.
22557       if (Mask[0] != 0 || Mask[1] != 1 ||
22558           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22559         return SDValue();
22560
22561       Chain.push_back(V);
22562       continue;
22563
22564     case X86ISD::PSHUFHW:
22565       // Check that the high words (being shuffled) are the identity in the
22566       // dword shuffle, and the low words are self-contained.
22567       if (Mask[2] != 2 || Mask[3] != 3 ||
22568           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22569         return SDValue();
22570
22571       Chain.push_back(V);
22572       continue;
22573
22574     case X86ISD::UNPCKL:
22575     case X86ISD::UNPCKH:
22576       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22577       // shuffle into a preceding word shuffle.
22578       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
22579         return SDValue();
22580
22581       // Search for a half-shuffle which we can combine with.
22582       unsigned CombineOp =
22583           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22584       if (V.getOperand(0) != V.getOperand(1) ||
22585           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22586         return SDValue();
22587       Chain.push_back(V);
22588       V = V.getOperand(0);
22589       do {
22590         switch (V.getOpcode()) {
22591         default:
22592           return SDValue(); // Nothing to combine.
22593
22594         case X86ISD::PSHUFLW:
22595         case X86ISD::PSHUFHW:
22596           if (V.getOpcode() == CombineOp)
22597             break;
22598
22599           Chain.push_back(V);
22600
22601           // Fallthrough!
22602         case ISD::BITCAST:
22603           V = V.getOperand(0);
22604           continue;
22605         }
22606         break;
22607       } while (V.hasOneUse());
22608       break;
22609     }
22610     // Break out of the loop if we break out of the switch.
22611     break;
22612   }
22613
22614   if (!V.hasOneUse())
22615     // We fell out of the loop without finding a viable combining instruction.
22616     return SDValue();
22617
22618   // Merge this node's mask and our incoming mask.
22619   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22620   for (int &M : Mask)
22621     M = VMask[M];
22622   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22623                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22624
22625   // Rebuild the chain around this new shuffle.
22626   while (!Chain.empty()) {
22627     SDValue W = Chain.pop_back_val();
22628
22629     if (V.getValueType() != W.getOperand(0).getValueType())
22630       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
22631
22632     switch (W.getOpcode()) {
22633     default:
22634       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22635
22636     case X86ISD::UNPCKL:
22637     case X86ISD::UNPCKH:
22638       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22639       break;
22640
22641     case X86ISD::PSHUFD:
22642     case X86ISD::PSHUFLW:
22643     case X86ISD::PSHUFHW:
22644       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22645       break;
22646     }
22647   }
22648   if (V.getValueType() != N.getValueType())
22649     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
22650
22651   // Return the new chain to replace N.
22652   return V;
22653 }
22654
22655 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22656 ///
22657 /// We walk up the chain, skipping shuffles of the other half and looking
22658 /// through shuffles which switch halves trying to find a shuffle of the same
22659 /// pair of dwords.
22660 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22661                                         SelectionDAG &DAG,
22662                                         TargetLowering::DAGCombinerInfo &DCI) {
22663   assert(
22664       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22665       "Called with something other than an x86 128-bit half shuffle!");
22666   SDLoc DL(N);
22667   unsigned CombineOpcode = N.getOpcode();
22668
22669   // Walk up a single-use chain looking for a combinable shuffle.
22670   SDValue V = N.getOperand(0);
22671   for (; V.hasOneUse(); V = V.getOperand(0)) {
22672     switch (V.getOpcode()) {
22673     default:
22674       return false; // Nothing combined!
22675
22676     case ISD::BITCAST:
22677       // Skip bitcasts as we always know the type for the target specific
22678       // instructions.
22679       continue;
22680
22681     case X86ISD::PSHUFLW:
22682     case X86ISD::PSHUFHW:
22683       if (V.getOpcode() == CombineOpcode)
22684         break;
22685
22686       // Other-half shuffles are no-ops.
22687       continue;
22688     }
22689     // Break out of the loop if we break out of the switch.
22690     break;
22691   }
22692
22693   if (!V.hasOneUse())
22694     // We fell out of the loop without finding a viable combining instruction.
22695     return false;
22696
22697   // Combine away the bottom node as its shuffle will be accumulated into
22698   // a preceding shuffle.
22699   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22700
22701   // Record the old value.
22702   SDValue Old = V;
22703
22704   // Merge this node's mask and our incoming mask (adjusted to account for all
22705   // the pshufd instructions encountered).
22706   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22707   for (int &M : Mask)
22708     M = VMask[M];
22709   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22710                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22711
22712   // Check that the shuffles didn't cancel each other out. If not, we need to
22713   // combine to the new one.
22714   if (Old != V)
22715     // Replace the combinable shuffle with the combined one, updating all users
22716     // so that we re-evaluate the chain here.
22717     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22718
22719   return true;
22720 }
22721
22722 /// \brief Try to combine x86 target specific shuffles.
22723 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22724                                            TargetLowering::DAGCombinerInfo &DCI,
22725                                            const X86Subtarget *Subtarget) {
22726   SDLoc DL(N);
22727   MVT VT = N.getSimpleValueType();
22728   SmallVector<int, 4> Mask;
22729
22730   switch (N.getOpcode()) {
22731   case X86ISD::PSHUFD:
22732   case X86ISD::PSHUFLW:
22733   case X86ISD::PSHUFHW:
22734     Mask = getPSHUFShuffleMask(N);
22735     assert(Mask.size() == 4);
22736     break;
22737   default:
22738     return SDValue();
22739   }
22740
22741   // Nuke no-op shuffles that show up after combining.
22742   if (isNoopShuffleMask(Mask))
22743     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22744
22745   // Look for simplifications involving one or two shuffle instructions.
22746   SDValue V = N.getOperand(0);
22747   switch (N.getOpcode()) {
22748   default:
22749     break;
22750   case X86ISD::PSHUFLW:
22751   case X86ISD::PSHUFHW:
22752     assert(VT == MVT::v8i16);
22753     (void)VT;
22754
22755     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22756       return SDValue(); // We combined away this shuffle, so we're done.
22757
22758     // See if this reduces to a PSHUFD which is no more expensive and can
22759     // combine with more operations. Note that it has to at least flip the
22760     // dwords as otherwise it would have been removed as a no-op.
22761     if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
22762       int DMask[] = {0, 1, 2, 3};
22763       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22764       DMask[DOffset + 0] = DOffset + 1;
22765       DMask[DOffset + 1] = DOffset + 0;
22766       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
22767       DCI.AddToWorklist(V.getNode());
22768       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
22769                       getV4X86ShuffleImm8ForMask(DMask, DAG));
22770       DCI.AddToWorklist(V.getNode());
22771       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
22772     }
22773
22774     // Look for shuffle patterns which can be implemented as a single unpack.
22775     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22776     // only works when we have a PSHUFD followed by two half-shuffles.
22777     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22778         (V.getOpcode() == X86ISD::PSHUFLW ||
22779          V.getOpcode() == X86ISD::PSHUFHW) &&
22780         V.getOpcode() != N.getOpcode() &&
22781         V.hasOneUse()) {
22782       SDValue D = V.getOperand(0);
22783       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22784         D = D.getOperand(0);
22785       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22786         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22787         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22788         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22789         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22790         int WordMask[8];
22791         for (int i = 0; i < 4; ++i) {
22792           WordMask[i + NOffset] = Mask[i] + NOffset;
22793           WordMask[i + VOffset] = VMask[i] + VOffset;
22794         }
22795         // Map the word mask through the DWord mask.
22796         int MappedMask[8];
22797         for (int i = 0; i < 8; ++i)
22798           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22799         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
22800         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
22801         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
22802                        std::begin(UnpackLoMask)) ||
22803             std::equal(std::begin(MappedMask), std::end(MappedMask),
22804                        std::begin(UnpackHiMask))) {
22805           // We can replace all three shuffles with an unpack.
22806           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
22807           DCI.AddToWorklist(V.getNode());
22808           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22809                                                 : X86ISD::UNPCKH,
22810                              DL, MVT::v8i16, V, V);
22811         }
22812       }
22813     }
22814
22815     break;
22816
22817   case X86ISD::PSHUFD:
22818     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22819       return NewN;
22820
22821     break;
22822   }
22823
22824   return SDValue();
22825 }
22826
22827 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22828 ///
22829 /// We combine this directly on the abstract vector shuffle nodes so it is
22830 /// easier to generically match. We also insert dummy vector shuffle nodes for
22831 /// the operands which explicitly discard the lanes which are unused by this
22832 /// operation to try to flow through the rest of the combiner the fact that
22833 /// they're unused.
22834 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22835   SDLoc DL(N);
22836   EVT VT = N->getValueType(0);
22837
22838   // We only handle target-independent shuffles.
22839   // FIXME: It would be easy and harmless to use the target shuffle mask
22840   // extraction tool to support more.
22841   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22842     return SDValue();
22843
22844   auto *SVN = cast<ShuffleVectorSDNode>(N);
22845   ArrayRef<int> Mask = SVN->getMask();
22846   SDValue V1 = N->getOperand(0);
22847   SDValue V2 = N->getOperand(1);
22848
22849   // We require the first shuffle operand to be the SUB node, and the second to
22850   // be the ADD node.
22851   // FIXME: We should support the commuted patterns.
22852   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22853     return SDValue();
22854
22855   // If there are other uses of these operations we can't fold them.
22856   if (!V1->hasOneUse() || !V2->hasOneUse())
22857     return SDValue();
22858
22859   // Ensure that both operations have the same operands. Note that we can
22860   // commute the FADD operands.
22861   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22862   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22863       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22864     return SDValue();
22865
22866   // We're looking for blends between FADD and FSUB nodes. We insist on these
22867   // nodes being lined up in a specific expected pattern.
22868   if (!(isShuffleEquivalent(Mask, 0, 3) ||
22869         isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
22870         isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
22871     return SDValue();
22872
22873   // Only specific types are legal at this point, assert so we notice if and
22874   // when these change.
22875   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22876           VT == MVT::v4f64) &&
22877          "Unknown vector type encountered!");
22878
22879   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22880 }
22881
22882 /// PerformShuffleCombine - Performs several different shuffle combines.
22883 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22884                                      TargetLowering::DAGCombinerInfo &DCI,
22885                                      const X86Subtarget *Subtarget) {
22886   SDLoc dl(N);
22887   SDValue N0 = N->getOperand(0);
22888   SDValue N1 = N->getOperand(1);
22889   EVT VT = N->getValueType(0);
22890
22891   // Don't create instructions with illegal types after legalize types has run.
22892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22893   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22894     return SDValue();
22895
22896   // If we have legalized the vector types, look for blends of FADD and FSUB
22897   // nodes that we can fuse into an ADDSUB node.
22898   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22899     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22900       return AddSub;
22901
22902   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22903   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22904       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22905     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22906
22907   // During Type Legalization, when promoting illegal vector types,
22908   // the backend might introduce new shuffle dag nodes and bitcasts.
22909   //
22910   // This code performs the following transformation:
22911   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22912   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22913   //
22914   // We do this only if both the bitcast and the BINOP dag nodes have
22915   // one use. Also, perform this transformation only if the new binary
22916   // operation is legal. This is to avoid introducing dag nodes that
22917   // potentially need to be further expanded (or custom lowered) into a
22918   // less optimal sequence of dag nodes.
22919   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22920       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22921       N0.getOpcode() == ISD::BITCAST) {
22922     SDValue BC0 = N0.getOperand(0);
22923     EVT SVT = BC0.getValueType();
22924     unsigned Opcode = BC0.getOpcode();
22925     unsigned NumElts = VT.getVectorNumElements();
22926
22927     if (BC0.hasOneUse() && SVT.isVector() &&
22928         SVT.getVectorNumElements() * 2 == NumElts &&
22929         TLI.isOperationLegal(Opcode, VT)) {
22930       bool CanFold = false;
22931       switch (Opcode) {
22932       default : break;
22933       case ISD::ADD :
22934       case ISD::FADD :
22935       case ISD::SUB :
22936       case ISD::FSUB :
22937       case ISD::MUL :
22938       case ISD::FMUL :
22939         CanFold = true;
22940       }
22941
22942       unsigned SVTNumElts = SVT.getVectorNumElements();
22943       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22944       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22945         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22946       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22947         CanFold = SVOp->getMaskElt(i) < 0;
22948
22949       if (CanFold) {
22950         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
22951         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
22952         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22953         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22954       }
22955     }
22956   }
22957
22958   // Only handle 128 wide vector from here on.
22959   if (!VT.is128BitVector())
22960     return SDValue();
22961
22962   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22963   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22964   // consecutive, non-overlapping, and in the right order.
22965   SmallVector<SDValue, 16> Elts;
22966   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22967     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22968
22969   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
22970   if (LD.getNode())
22971     return LD;
22972
22973   if (isTargetShuffle(N->getOpcode())) {
22974     SDValue Shuffle =
22975         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22976     if (Shuffle.getNode())
22977       return Shuffle;
22978
22979     // Try recursively combining arbitrary sequences of x86 shuffle
22980     // instructions into higher-order shuffles. We do this after combining
22981     // specific PSHUF instruction sequences into their minimal form so that we
22982     // can evaluate how many specialized shuffle instructions are involved in
22983     // a particular chain.
22984     SmallVector<int, 1> NonceMask; // Just a placeholder.
22985     NonceMask.push_back(0);
22986     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22987                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22988                                       DCI, Subtarget))
22989       return SDValue(); // This routine will use CombineTo to replace N.
22990   }
22991
22992   return SDValue();
22993 }
22994
22995 /// PerformTruncateCombine - Converts truncate operation to
22996 /// a sequence of vector shuffle operations.
22997 /// It is possible when we truncate 256-bit vector to 128-bit vector
22998 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
22999                                       TargetLowering::DAGCombinerInfo &DCI,
23000                                       const X86Subtarget *Subtarget)  {
23001   return SDValue();
23002 }
23003
23004 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23005 /// specific shuffle of a load can be folded into a single element load.
23006 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23007 /// shuffles have been custom lowered so we need to handle those here.
23008 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23009                                          TargetLowering::DAGCombinerInfo &DCI) {
23010   if (DCI.isBeforeLegalizeOps())
23011     return SDValue();
23012
23013   SDValue InVec = N->getOperand(0);
23014   SDValue EltNo = N->getOperand(1);
23015
23016   if (!isa<ConstantSDNode>(EltNo))
23017     return SDValue();
23018
23019   EVT OriginalVT = InVec.getValueType();
23020
23021   if (InVec.getOpcode() == ISD::BITCAST) {
23022     // Don't duplicate a load with other uses.
23023     if (!InVec.hasOneUse())
23024       return SDValue();
23025     EVT BCVT = InVec.getOperand(0).getValueType();
23026     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23027       return SDValue();
23028     InVec = InVec.getOperand(0);
23029   }
23030
23031   EVT CurrentVT = InVec.getValueType();
23032
23033   if (!isTargetShuffle(InVec.getOpcode()))
23034     return SDValue();
23035
23036   // Don't duplicate a load with other uses.
23037   if (!InVec.hasOneUse())
23038     return SDValue();
23039
23040   SmallVector<int, 16> ShuffleMask;
23041   bool UnaryShuffle;
23042   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23043                             ShuffleMask, UnaryShuffle))
23044     return SDValue();
23045
23046   // Select the input vector, guarding against out of range extract vector.
23047   unsigned NumElems = CurrentVT.getVectorNumElements();
23048   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23049   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23050   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23051                                          : InVec.getOperand(1);
23052
23053   // If inputs to shuffle are the same for both ops, then allow 2 uses
23054   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23055                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23056
23057   if (LdNode.getOpcode() == ISD::BITCAST) {
23058     // Don't duplicate a load with other uses.
23059     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23060       return SDValue();
23061
23062     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23063     LdNode = LdNode.getOperand(0);
23064   }
23065
23066   if (!ISD::isNormalLoad(LdNode.getNode()))
23067     return SDValue();
23068
23069   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23070
23071   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23072     return SDValue();
23073
23074   EVT EltVT = N->getValueType(0);
23075   // If there's a bitcast before the shuffle, check if the load type and
23076   // alignment is valid.
23077   unsigned Align = LN0->getAlignment();
23078   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23079   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
23080       EltVT.getTypeForEVT(*DAG.getContext()));
23081
23082   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23083     return SDValue();
23084
23085   // All checks match so transform back to vector_shuffle so that DAG combiner
23086   // can finish the job
23087   SDLoc dl(N);
23088
23089   // Create shuffle node taking into account the case that its a unary shuffle
23090   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23091                                    : InVec.getOperand(1);
23092   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23093                                  InVec.getOperand(0), Shuffle,
23094                                  &ShuffleMask[0]);
23095   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
23096   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23097                      EltNo);
23098 }
23099
23100 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23101 /// special and don't usually play with other vector types, it's better to
23102 /// handle them early to be sure we emit efficient code by avoiding
23103 /// store-load conversions.
23104 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
23105   if (N->getValueType(0) != MVT::x86mmx ||
23106       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
23107       N->getOperand(0)->getValueType(0) != MVT::v2i32)
23108     return SDValue();
23109
23110   SDValue V = N->getOperand(0);
23111   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
23112   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
23113     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
23114                        N->getValueType(0), V.getOperand(0));
23115
23116   return SDValue();
23117 }
23118
23119 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23120 /// generation and convert it from being a bunch of shuffles and extracts
23121 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23122 /// storing the value and loading scalars back, while for x64 we should
23123 /// use 64-bit extracts and shifts.
23124 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23125                                          TargetLowering::DAGCombinerInfo &DCI) {
23126   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
23127   if (NewOp.getNode())
23128     return NewOp;
23129
23130   SDValue InputVector = N->getOperand(0);
23131
23132   // Detect mmx to i32 conversion through a v2i32 elt extract.
23133   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23134       N->getValueType(0) == MVT::i32 &&
23135       InputVector.getValueType() == MVT::v2i32) {
23136
23137     // The bitcast source is a direct mmx result.
23138     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23139     if (MMXSrc.getValueType() == MVT::x86mmx)
23140       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23141                          N->getValueType(0),
23142                          InputVector.getNode()->getOperand(0));
23143
23144     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23145     SDValue MMXSrcOp = MMXSrc.getOperand(0);
23146     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23147         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
23148         MMXSrcOp.getOpcode() == ISD::BITCAST &&
23149         MMXSrcOp.getValueType() == MVT::v1i64 &&
23150         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23151       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23152                          N->getValueType(0),
23153                          MMXSrcOp.getOperand(0));
23154   }
23155
23156   // Only operate on vectors of 4 elements, where the alternative shuffling
23157   // gets to be more expensive.
23158   if (InputVector.getValueType() != MVT::v4i32)
23159     return SDValue();
23160
23161   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23162   // single use which is a sign-extend or zero-extend, and all elements are
23163   // used.
23164   SmallVector<SDNode *, 4> Uses;
23165   unsigned ExtractedElements = 0;
23166   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23167        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23168     if (UI.getUse().getResNo() != InputVector.getResNo())
23169       return SDValue();
23170
23171     SDNode *Extract = *UI;
23172     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23173       return SDValue();
23174
23175     if (Extract->getValueType(0) != MVT::i32)
23176       return SDValue();
23177     if (!Extract->hasOneUse())
23178       return SDValue();
23179     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23180         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23181       return SDValue();
23182     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23183       return SDValue();
23184
23185     // Record which element was extracted.
23186     ExtractedElements |=
23187       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23188
23189     Uses.push_back(Extract);
23190   }
23191
23192   // If not all the elements were used, this may not be worthwhile.
23193   if (ExtractedElements != 15)
23194     return SDValue();
23195
23196   // Ok, we've now decided to do the transformation.
23197   // If 64-bit shifts are legal, use the extract-shift sequence,
23198   // otherwise bounce the vector off the cache.
23199   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23200   SDValue Vals[4];
23201   SDLoc dl(InputVector);
23202
23203   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23204     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
23205     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
23206     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23207       DAG.getConstant(0, VecIdxTy));
23208     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23209       DAG.getConstant(1, VecIdxTy));
23210
23211     SDValue ShAmt = DAG.getConstant(32,
23212       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
23213     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23214     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23215       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23216     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23217     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23218       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23219   } else {
23220     // Store the value to a temporary stack slot.
23221     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23222     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23223       MachinePointerInfo(), false, false, 0);
23224
23225     EVT ElementType = InputVector.getValueType().getVectorElementType();
23226     unsigned EltSize = ElementType.getSizeInBits() / 8;
23227
23228     // Replace each use (extract) with a load of the appropriate element.
23229     for (unsigned i = 0; i < 4; ++i) {
23230       uint64_t Offset = EltSize * i;
23231       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
23232
23233       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
23234                                        StackPtr, OffsetVal);
23235
23236       // Load the scalar.
23237       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23238                             ScalarAddr, MachinePointerInfo(),
23239                             false, false, false, 0);
23240
23241     }
23242   }
23243
23244   // Replace the extracts
23245   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23246     UE = Uses.end(); UI != UE; ++UI) {
23247     SDNode *Extract = *UI;
23248
23249     SDValue Idx = Extract->getOperand(1);
23250     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23251     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23252   }
23253
23254   // The replacement was made in place; don't return anything.
23255   return SDValue();
23256 }
23257
23258 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
23259 static std::pair<unsigned, bool>
23260 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
23261                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
23262   if (!VT.isVector())
23263     return std::make_pair(0, false);
23264
23265   bool NeedSplit = false;
23266   switch (VT.getSimpleVT().SimpleTy) {
23267   default: return std::make_pair(0, false);
23268   case MVT::v4i64:
23269   case MVT::v2i64:
23270     if (!Subtarget->hasVLX())
23271       return std::make_pair(0, false);
23272     break;
23273   case MVT::v64i8:
23274   case MVT::v32i16:
23275     if (!Subtarget->hasBWI())
23276       return std::make_pair(0, false);
23277     break;
23278   case MVT::v16i32:
23279   case MVT::v8i64:
23280     if (!Subtarget->hasAVX512())
23281       return std::make_pair(0, false);
23282     break;
23283   case MVT::v32i8:
23284   case MVT::v16i16:
23285   case MVT::v8i32:
23286     if (!Subtarget->hasAVX2())
23287       NeedSplit = true;
23288     if (!Subtarget->hasAVX())
23289       return std::make_pair(0, false);
23290     break;
23291   case MVT::v16i8:
23292   case MVT::v8i16:
23293   case MVT::v4i32:
23294     if (!Subtarget->hasSSE2())
23295       return std::make_pair(0, false);
23296   }
23297
23298   // SSE2 has only a small subset of the operations.
23299   bool hasUnsigned = Subtarget->hasSSE41() ||
23300                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
23301   bool hasSigned = Subtarget->hasSSE41() ||
23302                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
23303
23304   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23305
23306   unsigned Opc = 0;
23307   // Check for x CC y ? x : y.
23308   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23309       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23310     switch (CC) {
23311     default: break;
23312     case ISD::SETULT:
23313     case ISD::SETULE:
23314       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
23315     case ISD::SETUGT:
23316     case ISD::SETUGE:
23317       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
23318     case ISD::SETLT:
23319     case ISD::SETLE:
23320       Opc = hasSigned ? X86ISD::SMIN : 0; break;
23321     case ISD::SETGT:
23322     case ISD::SETGE:
23323       Opc = hasSigned ? X86ISD::SMAX : 0; break;
23324     }
23325   // Check for x CC y ? y : x -- a min/max with reversed arms.
23326   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23327              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23328     switch (CC) {
23329     default: break;
23330     case ISD::SETULT:
23331     case ISD::SETULE:
23332       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
23333     case ISD::SETUGT:
23334     case ISD::SETUGE:
23335       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
23336     case ISD::SETLT:
23337     case ISD::SETLE:
23338       Opc = hasSigned ? X86ISD::SMAX : 0; break;
23339     case ISD::SETGT:
23340     case ISD::SETGE:
23341       Opc = hasSigned ? X86ISD::SMIN : 0; break;
23342     }
23343   }
23344
23345   return std::make_pair(Opc, NeedSplit);
23346 }
23347
23348 static SDValue
23349 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23350                                       const X86Subtarget *Subtarget) {
23351   SDLoc dl(N);
23352   SDValue Cond = N->getOperand(0);
23353   SDValue LHS = N->getOperand(1);
23354   SDValue RHS = N->getOperand(2);
23355
23356   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23357     SDValue CondSrc = Cond->getOperand(0);
23358     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23359       Cond = CondSrc->getOperand(0);
23360   }
23361
23362   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23363     return SDValue();
23364
23365   // A vselect where all conditions and data are constants can be optimized into
23366   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23367   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23368       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23369     return SDValue();
23370
23371   unsigned MaskValue = 0;
23372   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23373     return SDValue();
23374
23375   MVT VT = N->getSimpleValueType(0);
23376   unsigned NumElems = VT.getVectorNumElements();
23377   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23378   for (unsigned i = 0; i < NumElems; ++i) {
23379     // Be sure we emit undef where we can.
23380     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23381       ShuffleMask[i] = -1;
23382     else
23383       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23384   }
23385
23386   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23387   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23388     return SDValue();
23389   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23390 }
23391
23392 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23393 /// nodes.
23394 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23395                                     TargetLowering::DAGCombinerInfo &DCI,
23396                                     const X86Subtarget *Subtarget) {
23397   SDLoc DL(N);
23398   SDValue Cond = N->getOperand(0);
23399   // Get the LHS/RHS of the select.
23400   SDValue LHS = N->getOperand(1);
23401   SDValue RHS = N->getOperand(2);
23402   EVT VT = LHS.getValueType();
23403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23404
23405   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23406   // instructions match the semantics of the common C idiom x<y?x:y but not
23407   // x<=y?x:y, because of how they handle negative zero (which can be
23408   // ignored in unsafe-math mode).
23409   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23410   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23411       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23412       (Subtarget->hasSSE2() ||
23413        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23414     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23415
23416     unsigned Opcode = 0;
23417     // Check for x CC y ? x : y.
23418     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23419         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23420       switch (CC) {
23421       default: break;
23422       case ISD::SETULT:
23423         // Converting this to a min would handle NaNs incorrectly, and swapping
23424         // the operands would cause it to handle comparisons between positive
23425         // and negative zero incorrectly.
23426         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23427           if (!DAG.getTarget().Options.UnsafeFPMath &&
23428               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23429             break;
23430           std::swap(LHS, RHS);
23431         }
23432         Opcode = X86ISD::FMIN;
23433         break;
23434       case ISD::SETOLE:
23435         // Converting this to a min would handle comparisons between positive
23436         // and negative zero incorrectly.
23437         if (!DAG.getTarget().Options.UnsafeFPMath &&
23438             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23439           break;
23440         Opcode = X86ISD::FMIN;
23441         break;
23442       case ISD::SETULE:
23443         // Converting this to a min would handle both negative zeros and NaNs
23444         // incorrectly, but we can swap the operands to fix both.
23445         std::swap(LHS, RHS);
23446       case ISD::SETOLT:
23447       case ISD::SETLT:
23448       case ISD::SETLE:
23449         Opcode = X86ISD::FMIN;
23450         break;
23451
23452       case ISD::SETOGE:
23453         // Converting this to a max would handle comparisons between positive
23454         // and negative zero incorrectly.
23455         if (!DAG.getTarget().Options.UnsafeFPMath &&
23456             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23457           break;
23458         Opcode = X86ISD::FMAX;
23459         break;
23460       case ISD::SETUGT:
23461         // Converting this to a max would handle NaNs incorrectly, and swapping
23462         // the operands would cause it to handle comparisons between positive
23463         // and negative zero incorrectly.
23464         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23465           if (!DAG.getTarget().Options.UnsafeFPMath &&
23466               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23467             break;
23468           std::swap(LHS, RHS);
23469         }
23470         Opcode = X86ISD::FMAX;
23471         break;
23472       case ISD::SETUGE:
23473         // Converting this to a max would handle both negative zeros and NaNs
23474         // incorrectly, but we can swap the operands to fix both.
23475         std::swap(LHS, RHS);
23476       case ISD::SETOGT:
23477       case ISD::SETGT:
23478       case ISD::SETGE:
23479         Opcode = X86ISD::FMAX;
23480         break;
23481       }
23482     // Check for x CC y ? y : x -- a min/max with reversed arms.
23483     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23484                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23485       switch (CC) {
23486       default: break;
23487       case ISD::SETOGE:
23488         // Converting this to a min would handle comparisons between positive
23489         // and negative zero incorrectly, and swapping the operands would
23490         // cause it to handle NaNs incorrectly.
23491         if (!DAG.getTarget().Options.UnsafeFPMath &&
23492             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23493           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23494             break;
23495           std::swap(LHS, RHS);
23496         }
23497         Opcode = X86ISD::FMIN;
23498         break;
23499       case ISD::SETUGT:
23500         // Converting this to a min would handle NaNs incorrectly.
23501         if (!DAG.getTarget().Options.UnsafeFPMath &&
23502             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23503           break;
23504         Opcode = X86ISD::FMIN;
23505         break;
23506       case ISD::SETUGE:
23507         // Converting this to a min would handle both negative zeros and NaNs
23508         // incorrectly, but we can swap the operands to fix both.
23509         std::swap(LHS, RHS);
23510       case ISD::SETOGT:
23511       case ISD::SETGT:
23512       case ISD::SETGE:
23513         Opcode = X86ISD::FMIN;
23514         break;
23515
23516       case ISD::SETULT:
23517         // Converting this to a max would handle NaNs incorrectly.
23518         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23519           break;
23520         Opcode = X86ISD::FMAX;
23521         break;
23522       case ISD::SETOLE:
23523         // Converting this to a max would handle comparisons between positive
23524         // and negative zero incorrectly, and swapping the operands would
23525         // cause it to handle NaNs incorrectly.
23526         if (!DAG.getTarget().Options.UnsafeFPMath &&
23527             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23528           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23529             break;
23530           std::swap(LHS, RHS);
23531         }
23532         Opcode = X86ISD::FMAX;
23533         break;
23534       case ISD::SETULE:
23535         // Converting this to a max would handle both negative zeros and NaNs
23536         // incorrectly, but we can swap the operands to fix both.
23537         std::swap(LHS, RHS);
23538       case ISD::SETOLT:
23539       case ISD::SETLT:
23540       case ISD::SETLE:
23541         Opcode = X86ISD::FMAX;
23542         break;
23543       }
23544     }
23545
23546     if (Opcode)
23547       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23548   }
23549
23550   EVT CondVT = Cond.getValueType();
23551   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23552       CondVT.getVectorElementType() == MVT::i1) {
23553     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23554     // lowering on KNL. In this case we convert it to
23555     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23556     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23557     // Since SKX these selects have a proper lowering.
23558     EVT OpVT = LHS.getValueType();
23559     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23560         (OpVT.getVectorElementType() == MVT::i8 ||
23561          OpVT.getVectorElementType() == MVT::i16) &&
23562         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23563       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23564       DCI.AddToWorklist(Cond.getNode());
23565       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23566     }
23567   }
23568   // If this is a select between two integer constants, try to do some
23569   // optimizations.
23570   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23571     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23572       // Don't do this for crazy integer types.
23573       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23574         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23575         // so that TrueC (the true value) is larger than FalseC.
23576         bool NeedsCondInvert = false;
23577
23578         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23579             // Efficiently invertible.
23580             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23581              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23582               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23583           NeedsCondInvert = true;
23584           std::swap(TrueC, FalseC);
23585         }
23586
23587         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23588         if (FalseC->getAPIntValue() == 0 &&
23589             TrueC->getAPIntValue().isPowerOf2()) {
23590           if (NeedsCondInvert) // Invert the condition if needed.
23591             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23592                                DAG.getConstant(1, Cond.getValueType()));
23593
23594           // Zero extend the condition if needed.
23595           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23596
23597           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23598           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23599                              DAG.getConstant(ShAmt, MVT::i8));
23600         }
23601
23602         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23603         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23604           if (NeedsCondInvert) // Invert the condition if needed.
23605             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23606                                DAG.getConstant(1, Cond.getValueType()));
23607
23608           // Zero extend the condition if needed.
23609           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23610                              FalseC->getValueType(0), Cond);
23611           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23612                              SDValue(FalseC, 0));
23613         }
23614
23615         // Optimize cases that will turn into an LEA instruction.  This requires
23616         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23617         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23618           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23619           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23620
23621           bool isFastMultiplier = false;
23622           if (Diff < 10) {
23623             switch ((unsigned char)Diff) {
23624               default: break;
23625               case 1:  // result = add base, cond
23626               case 2:  // result = lea base(    , cond*2)
23627               case 3:  // result = lea base(cond, cond*2)
23628               case 4:  // result = lea base(    , cond*4)
23629               case 5:  // result = lea base(cond, cond*4)
23630               case 8:  // result = lea base(    , cond*8)
23631               case 9:  // result = lea base(cond, cond*8)
23632                 isFastMultiplier = true;
23633                 break;
23634             }
23635           }
23636
23637           if (isFastMultiplier) {
23638             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23639             if (NeedsCondInvert) // Invert the condition if needed.
23640               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23641                                  DAG.getConstant(1, Cond.getValueType()));
23642
23643             // Zero extend the condition if needed.
23644             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23645                                Cond);
23646             // Scale the condition by the difference.
23647             if (Diff != 1)
23648               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23649                                  DAG.getConstant(Diff, Cond.getValueType()));
23650
23651             // Add the base if non-zero.
23652             if (FalseC->getAPIntValue() != 0)
23653               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23654                                  SDValue(FalseC, 0));
23655             return Cond;
23656           }
23657         }
23658       }
23659   }
23660
23661   // Canonicalize max and min:
23662   // (x > y) ? x : y -> (x >= y) ? x : y
23663   // (x < y) ? x : y -> (x <= y) ? x : y
23664   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23665   // the need for an extra compare
23666   // against zero. e.g.
23667   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23668   // subl   %esi, %edi
23669   // testl  %edi, %edi
23670   // movl   $0, %eax
23671   // cmovgl %edi, %eax
23672   // =>
23673   // xorl   %eax, %eax
23674   // subl   %esi, $edi
23675   // cmovsl %eax, %edi
23676   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23677       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23678       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23679     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23680     switch (CC) {
23681     default: break;
23682     case ISD::SETLT:
23683     case ISD::SETGT: {
23684       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23685       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23686                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23687       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23688     }
23689     }
23690   }
23691
23692   // Early exit check
23693   if (!TLI.isTypeLegal(VT))
23694     return SDValue();
23695
23696   // Match VSELECTs into subs with unsigned saturation.
23697   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23698       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23699       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23700        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23701     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23702
23703     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23704     // left side invert the predicate to simplify logic below.
23705     SDValue Other;
23706     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23707       Other = RHS;
23708       CC = ISD::getSetCCInverse(CC, true);
23709     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23710       Other = LHS;
23711     }
23712
23713     if (Other.getNode() && Other->getNumOperands() == 2 &&
23714         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23715       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23716       SDValue CondRHS = Cond->getOperand(1);
23717
23718       // Look for a general sub with unsigned saturation first.
23719       // x >= y ? x-y : 0 --> subus x, y
23720       // x >  y ? x-y : 0 --> subus x, y
23721       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23722           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23723         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23724
23725       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23726         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23727           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23728             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23729               // If the RHS is a constant we have to reverse the const
23730               // canonicalization.
23731               // x > C-1 ? x+-C : 0 --> subus x, C
23732               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23733                   CondRHSConst->getAPIntValue() ==
23734                       (-OpRHSConst->getAPIntValue() - 1))
23735                 return DAG.getNode(
23736                     X86ISD::SUBUS, DL, VT, OpLHS,
23737                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
23738
23739           // Another special case: If C was a sign bit, the sub has been
23740           // canonicalized into a xor.
23741           // FIXME: Would it be better to use computeKnownBits to determine
23742           //        whether it's safe to decanonicalize the xor?
23743           // x s< 0 ? x^C : 0 --> subus x, C
23744           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23745               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23746               OpRHSConst->getAPIntValue().isSignBit())
23747             // Note that we have to rebuild the RHS constant here to ensure we
23748             // don't rely on particular values of undef lanes.
23749             return DAG.getNode(
23750                 X86ISD::SUBUS, DL, VT, OpLHS,
23751                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
23752         }
23753     }
23754   }
23755
23756   // Try to match a min/max vector operation.
23757   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
23758     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
23759     unsigned Opc = ret.first;
23760     bool NeedSplit = ret.second;
23761
23762     if (Opc && NeedSplit) {
23763       unsigned NumElems = VT.getVectorNumElements();
23764       // Extract the LHS vectors
23765       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
23766       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
23767
23768       // Extract the RHS vectors
23769       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
23770       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
23771
23772       // Create min/max for each subvector
23773       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
23774       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
23775
23776       // Merge the result
23777       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
23778     } else if (Opc)
23779       return DAG.getNode(Opc, DL, VT, LHS, RHS);
23780   }
23781
23782   // Simplify vector selection if condition value type matches vselect
23783   // operand type
23784   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23785     assert(Cond.getValueType().isVector() &&
23786            "vector select expects a vector selector!");
23787
23788     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23789     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23790
23791     // Try invert the condition if true value is not all 1s and false value
23792     // is not all 0s.
23793     if (!TValIsAllOnes && !FValIsAllZeros &&
23794         // Check if the selector will be produced by CMPP*/PCMP*
23795         Cond.getOpcode() == ISD::SETCC &&
23796         // Check if SETCC has already been promoted
23797         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
23798       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23799       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23800
23801       if (TValIsAllZeros || FValIsAllOnes) {
23802         SDValue CC = Cond.getOperand(2);
23803         ISD::CondCode NewCC =
23804           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23805                                Cond.getOperand(0).getValueType().isInteger());
23806         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23807         std::swap(LHS, RHS);
23808         TValIsAllOnes = FValIsAllOnes;
23809         FValIsAllZeros = TValIsAllZeros;
23810       }
23811     }
23812
23813     if (TValIsAllOnes || FValIsAllZeros) {
23814       SDValue Ret;
23815
23816       if (TValIsAllOnes && FValIsAllZeros)
23817         Ret = Cond;
23818       else if (TValIsAllOnes)
23819         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
23820                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
23821       else if (FValIsAllZeros)
23822         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23823                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
23824
23825       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
23826     }
23827   }
23828
23829   // If we know that this node is legal then we know that it is going to be
23830   // matched by one of the SSE/AVX BLEND instructions. These instructions only
23831   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
23832   // to simplify previous instructions.
23833   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23834       !DCI.isBeforeLegalize() &&
23835       // We explicitly check against v8i16 and v16i16 because, although
23836       // they're marked as Custom, they might only be legal when Cond is a
23837       // build_vector of constants. This will be taken care in a later
23838       // condition.
23839       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
23840        VT != MVT::v8i16) &&
23841       // Don't optimize vector of constants. Those are handled by
23842       // the generic code and all the bits must be properly set for
23843       // the generic optimizer.
23844       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23845     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23846
23847     // Don't optimize vector selects that map to mask-registers.
23848     if (BitWidth == 1)
23849       return SDValue();
23850
23851     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23852     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23853
23854     APInt KnownZero, KnownOne;
23855     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23856                                           DCI.isBeforeLegalizeOps());
23857     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23858         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23859                                  TLO)) {
23860       // If we changed the computation somewhere in the DAG, this change
23861       // will affect all users of Cond.
23862       // Make sure it is fine and update all the nodes so that we do not
23863       // use the generic VSELECT anymore. Otherwise, we may perform
23864       // wrong optimizations as we messed up with the actual expectation
23865       // for the vector boolean values.
23866       if (Cond != TLO.Old) {
23867         // Check all uses of that condition operand to check whether it will be
23868         // consumed by non-BLEND instructions, which may depend on all bits are
23869         // set properly.
23870         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23871              I != E; ++I)
23872           if (I->getOpcode() != ISD::VSELECT)
23873             // TODO: Add other opcodes eventually lowered into BLEND.
23874             return SDValue();
23875
23876         // Update all the users of the condition, before committing the change,
23877         // so that the VSELECT optimizations that expect the correct vector
23878         // boolean value will not be triggered.
23879         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23880              I != E; ++I)
23881           DAG.ReplaceAllUsesOfValueWith(
23882               SDValue(*I, 0),
23883               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23884                           Cond, I->getOperand(1), I->getOperand(2)));
23885         DCI.CommitTargetLoweringOpt(TLO);
23886         return SDValue();
23887       }
23888       // At this point, only Cond is changed. Change the condition
23889       // just for N to keep the opportunity to optimize all other
23890       // users their own way.
23891       DAG.ReplaceAllUsesOfValueWith(
23892           SDValue(N, 0),
23893           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23894                       TLO.New, N->getOperand(1), N->getOperand(2)));
23895       return SDValue();
23896     }
23897   }
23898
23899   // We should generate an X86ISD::BLENDI from a vselect if its argument
23900   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23901   // constants. This specific pattern gets generated when we split a
23902   // selector for a 512 bit vector in a machine without AVX512 (but with
23903   // 256-bit vectors), during legalization:
23904   //
23905   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23906   //
23907   // Iff we find this pattern and the build_vectors are built from
23908   // constants, we translate the vselect into a shuffle_vector that we
23909   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23910   if ((N->getOpcode() == ISD::VSELECT ||
23911        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23912       !DCI.isBeforeLegalize()) {
23913     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23914     if (Shuffle.getNode())
23915       return Shuffle;
23916   }
23917
23918   return SDValue();
23919 }
23920
23921 // Check whether a boolean test is testing a boolean value generated by
23922 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23923 // code.
23924 //
23925 // Simplify the following patterns:
23926 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23927 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23928 // to (Op EFLAGS Cond)
23929 //
23930 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23931 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23932 // to (Op EFLAGS !Cond)
23933 //
23934 // where Op could be BRCOND or CMOV.
23935 //
23936 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23937   // Quit if not CMP and SUB with its value result used.
23938   if (Cmp.getOpcode() != X86ISD::CMP &&
23939       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23940       return SDValue();
23941
23942   // Quit if not used as a boolean value.
23943   if (CC != X86::COND_E && CC != X86::COND_NE)
23944     return SDValue();
23945
23946   // Check CMP operands. One of them should be 0 or 1 and the other should be
23947   // an SetCC or extended from it.
23948   SDValue Op1 = Cmp.getOperand(0);
23949   SDValue Op2 = Cmp.getOperand(1);
23950
23951   SDValue SetCC;
23952   const ConstantSDNode* C = nullptr;
23953   bool needOppositeCond = (CC == X86::COND_E);
23954   bool checkAgainstTrue = false; // Is it a comparison against 1?
23955
23956   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23957     SetCC = Op2;
23958   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23959     SetCC = Op1;
23960   else // Quit if all operands are not constants.
23961     return SDValue();
23962
23963   if (C->getZExtValue() == 1) {
23964     needOppositeCond = !needOppositeCond;
23965     checkAgainstTrue = true;
23966   } else if (C->getZExtValue() != 0)
23967     // Quit if the constant is neither 0 or 1.
23968     return SDValue();
23969
23970   bool truncatedToBoolWithAnd = false;
23971   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23972   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23973          SetCC.getOpcode() == ISD::TRUNCATE ||
23974          SetCC.getOpcode() == ISD::AND) {
23975     if (SetCC.getOpcode() == ISD::AND) {
23976       int OpIdx = -1;
23977       ConstantSDNode *CS;
23978       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23979           CS->getZExtValue() == 1)
23980         OpIdx = 1;
23981       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23982           CS->getZExtValue() == 1)
23983         OpIdx = 0;
23984       if (OpIdx == -1)
23985         break;
23986       SetCC = SetCC.getOperand(OpIdx);
23987       truncatedToBoolWithAnd = true;
23988     } else
23989       SetCC = SetCC.getOperand(0);
23990   }
23991
23992   switch (SetCC.getOpcode()) {
23993   case X86ISD::SETCC_CARRY:
23994     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23995     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23996     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23997     // truncated to i1 using 'and'.
23998     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23999       break;
24000     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24001            "Invalid use of SETCC_CARRY!");
24002     // FALL THROUGH
24003   case X86ISD::SETCC:
24004     // Set the condition code or opposite one if necessary.
24005     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24006     if (needOppositeCond)
24007       CC = X86::GetOppositeBranchCondition(CC);
24008     return SetCC.getOperand(1);
24009   case X86ISD::CMOV: {
24010     // Check whether false/true value has canonical one, i.e. 0 or 1.
24011     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24012     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24013     // Quit if true value is not a constant.
24014     if (!TVal)
24015       return SDValue();
24016     // Quit if false value is not a constant.
24017     if (!FVal) {
24018       SDValue Op = SetCC.getOperand(0);
24019       // Skip 'zext' or 'trunc' node.
24020       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24021           Op.getOpcode() == ISD::TRUNCATE)
24022         Op = Op.getOperand(0);
24023       // A special case for rdrand/rdseed, where 0 is set if false cond is
24024       // found.
24025       if ((Op.getOpcode() != X86ISD::RDRAND &&
24026            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24027         return SDValue();
24028     }
24029     // Quit if false value is not the constant 0 or 1.
24030     bool FValIsFalse = true;
24031     if (FVal && FVal->getZExtValue() != 0) {
24032       if (FVal->getZExtValue() != 1)
24033         return SDValue();
24034       // If FVal is 1, opposite cond is needed.
24035       needOppositeCond = !needOppositeCond;
24036       FValIsFalse = false;
24037     }
24038     // Quit if TVal is not the constant opposite of FVal.
24039     if (FValIsFalse && TVal->getZExtValue() != 1)
24040       return SDValue();
24041     if (!FValIsFalse && TVal->getZExtValue() != 0)
24042       return SDValue();
24043     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24044     if (needOppositeCond)
24045       CC = X86::GetOppositeBranchCondition(CC);
24046     return SetCC.getOperand(3);
24047   }
24048   }
24049
24050   return SDValue();
24051 }
24052
24053 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24054 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24055                                   TargetLowering::DAGCombinerInfo &DCI,
24056                                   const X86Subtarget *Subtarget) {
24057   SDLoc DL(N);
24058
24059   // If the flag operand isn't dead, don't touch this CMOV.
24060   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24061     return SDValue();
24062
24063   SDValue FalseOp = N->getOperand(0);
24064   SDValue TrueOp = N->getOperand(1);
24065   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24066   SDValue Cond = N->getOperand(3);
24067
24068   if (CC == X86::COND_E || CC == X86::COND_NE) {
24069     switch (Cond.getOpcode()) {
24070     default: break;
24071     case X86ISD::BSR:
24072     case X86ISD::BSF:
24073       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24074       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24075         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24076     }
24077   }
24078
24079   SDValue Flags;
24080
24081   Flags = checkBoolTestSetCCCombine(Cond, CC);
24082   if (Flags.getNode() &&
24083       // Extra check as FCMOV only supports a subset of X86 cond.
24084       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24085     SDValue Ops[] = { FalseOp, TrueOp,
24086                       DAG.getConstant(CC, MVT::i8), Flags };
24087     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24088   }
24089
24090   // If this is a select between two integer constants, try to do some
24091   // optimizations.  Note that the operands are ordered the opposite of SELECT
24092   // operands.
24093   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24094     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24095       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24096       // larger than FalseC (the false value).
24097       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24098         CC = X86::GetOppositeBranchCondition(CC);
24099         std::swap(TrueC, FalseC);
24100         std::swap(TrueOp, FalseOp);
24101       }
24102
24103       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24104       // This is efficient for any integer data type (including i8/i16) and
24105       // shift amount.
24106       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24107         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24108                            DAG.getConstant(CC, MVT::i8), Cond);
24109
24110         // Zero extend the condition if needed.
24111         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24112
24113         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24114         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24115                            DAG.getConstant(ShAmt, MVT::i8));
24116         if (N->getNumValues() == 2)  // Dead flag value?
24117           return DCI.CombineTo(N, Cond, SDValue());
24118         return Cond;
24119       }
24120
24121       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24122       // for any integer data type, including i8/i16.
24123       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24124         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24125                            DAG.getConstant(CC, MVT::i8), Cond);
24126
24127         // Zero extend the condition if needed.
24128         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24129                            FalseC->getValueType(0), Cond);
24130         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24131                            SDValue(FalseC, 0));
24132
24133         if (N->getNumValues() == 2)  // Dead flag value?
24134           return DCI.CombineTo(N, Cond, SDValue());
24135         return Cond;
24136       }
24137
24138       // Optimize cases that will turn into an LEA instruction.  This requires
24139       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24140       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24141         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24142         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24143
24144         bool isFastMultiplier = false;
24145         if (Diff < 10) {
24146           switch ((unsigned char)Diff) {
24147           default: break;
24148           case 1:  // result = add base, cond
24149           case 2:  // result = lea base(    , cond*2)
24150           case 3:  // result = lea base(cond, cond*2)
24151           case 4:  // result = lea base(    , cond*4)
24152           case 5:  // result = lea base(cond, cond*4)
24153           case 8:  // result = lea base(    , cond*8)
24154           case 9:  // result = lea base(cond, cond*8)
24155             isFastMultiplier = true;
24156             break;
24157           }
24158         }
24159
24160         if (isFastMultiplier) {
24161           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24162           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24163                              DAG.getConstant(CC, MVT::i8), Cond);
24164           // Zero extend the condition if needed.
24165           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24166                              Cond);
24167           // Scale the condition by the difference.
24168           if (Diff != 1)
24169             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24170                                DAG.getConstant(Diff, Cond.getValueType()));
24171
24172           // Add the base if non-zero.
24173           if (FalseC->getAPIntValue() != 0)
24174             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24175                                SDValue(FalseC, 0));
24176           if (N->getNumValues() == 2)  // Dead flag value?
24177             return DCI.CombineTo(N, Cond, SDValue());
24178           return Cond;
24179         }
24180       }
24181     }
24182   }
24183
24184   // Handle these cases:
24185   //   (select (x != c), e, c) -> select (x != c), e, x),
24186   //   (select (x == c), c, e) -> select (x == c), x, e)
24187   // where the c is an integer constant, and the "select" is the combination
24188   // of CMOV and CMP.
24189   //
24190   // The rationale for this change is that the conditional-move from a constant
24191   // needs two instructions, however, conditional-move from a register needs
24192   // only one instruction.
24193   //
24194   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24195   //  some instruction-combining opportunities. This opt needs to be
24196   //  postponed as late as possible.
24197   //
24198   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24199     // the DCI.xxxx conditions are provided to postpone the optimization as
24200     // late as possible.
24201
24202     ConstantSDNode *CmpAgainst = nullptr;
24203     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24204         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24205         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24206
24207       if (CC == X86::COND_NE &&
24208           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24209         CC = X86::GetOppositeBranchCondition(CC);
24210         std::swap(TrueOp, FalseOp);
24211       }
24212
24213       if (CC == X86::COND_E &&
24214           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24215         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24216                           DAG.getConstant(CC, MVT::i8), Cond };
24217         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24218       }
24219     }
24220   }
24221
24222   return SDValue();
24223 }
24224
24225 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
24226                                                 const X86Subtarget *Subtarget) {
24227   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
24228   switch (IntNo) {
24229   default: return SDValue();
24230   // SSE/AVX/AVX2 blend intrinsics.
24231   case Intrinsic::x86_avx2_pblendvb:
24232   case Intrinsic::x86_avx2_pblendw:
24233   case Intrinsic::x86_avx2_pblendd_128:
24234   case Intrinsic::x86_avx2_pblendd_256:
24235     // Don't try to simplify this intrinsic if we don't have AVX2.
24236     if (!Subtarget->hasAVX2())
24237       return SDValue();
24238     // FALL-THROUGH
24239   case Intrinsic::x86_avx_blend_pd_256:
24240   case Intrinsic::x86_avx_blend_ps_256:
24241   case Intrinsic::x86_avx_blendv_pd_256:
24242   case Intrinsic::x86_avx_blendv_ps_256:
24243     // Don't try to simplify this intrinsic if we don't have AVX.
24244     if (!Subtarget->hasAVX())
24245       return SDValue();
24246     // FALL-THROUGH
24247   case Intrinsic::x86_sse41_pblendw:
24248   case Intrinsic::x86_sse41_blendpd:
24249   case Intrinsic::x86_sse41_blendps:
24250   case Intrinsic::x86_sse41_blendvps:
24251   case Intrinsic::x86_sse41_blendvpd:
24252   case Intrinsic::x86_sse41_pblendvb: {
24253     SDValue Op0 = N->getOperand(1);
24254     SDValue Op1 = N->getOperand(2);
24255     SDValue Mask = N->getOperand(3);
24256
24257     // Don't try to simplify this intrinsic if we don't have SSE4.1.
24258     if (!Subtarget->hasSSE41())
24259       return SDValue();
24260
24261     // fold (blend A, A, Mask) -> A
24262     if (Op0 == Op1)
24263       return Op0;
24264     // fold (blend A, B, allZeros) -> A
24265     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
24266       return Op0;
24267     // fold (blend A, B, allOnes) -> B
24268     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
24269       return Op1;
24270
24271     // Simplify the case where the mask is a constant i32 value.
24272     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
24273       if (C->isNullValue())
24274         return Op0;
24275       if (C->isAllOnesValue())
24276         return Op1;
24277     }
24278
24279     return SDValue();
24280   }
24281
24282   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
24283   case Intrinsic::x86_sse2_psrai_w:
24284   case Intrinsic::x86_sse2_psrai_d:
24285   case Intrinsic::x86_avx2_psrai_w:
24286   case Intrinsic::x86_avx2_psrai_d:
24287   case Intrinsic::x86_sse2_psra_w:
24288   case Intrinsic::x86_sse2_psra_d:
24289   case Intrinsic::x86_avx2_psra_w:
24290   case Intrinsic::x86_avx2_psra_d: {
24291     SDValue Op0 = N->getOperand(1);
24292     SDValue Op1 = N->getOperand(2);
24293     EVT VT = Op0.getValueType();
24294     assert(VT.isVector() && "Expected a vector type!");
24295
24296     if (isa<BuildVectorSDNode>(Op1))
24297       Op1 = Op1.getOperand(0);
24298
24299     if (!isa<ConstantSDNode>(Op1))
24300       return SDValue();
24301
24302     EVT SVT = VT.getVectorElementType();
24303     unsigned SVTBits = SVT.getSizeInBits();
24304
24305     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
24306     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
24307     uint64_t ShAmt = C.getZExtValue();
24308
24309     // Don't try to convert this shift into a ISD::SRA if the shift
24310     // count is bigger than or equal to the element size.
24311     if (ShAmt >= SVTBits)
24312       return SDValue();
24313
24314     // Trivial case: if the shift count is zero, then fold this
24315     // into the first operand.
24316     if (ShAmt == 0)
24317       return Op0;
24318
24319     // Replace this packed shift intrinsic with a target independent
24320     // shift dag node.
24321     SDValue Splat = DAG.getConstant(C, VT);
24322     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
24323   }
24324   }
24325 }
24326
24327 /// PerformMulCombine - Optimize a single multiply with constant into two
24328 /// in order to implement it with two cheaper instructions, e.g.
24329 /// LEA + SHL, LEA + LEA.
24330 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24331                                  TargetLowering::DAGCombinerInfo &DCI) {
24332   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24333     return SDValue();
24334
24335   EVT VT = N->getValueType(0);
24336   if (VT != MVT::i64 && VT != MVT::i32)
24337     return SDValue();
24338
24339   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24340   if (!C)
24341     return SDValue();
24342   uint64_t MulAmt = C->getZExtValue();
24343   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24344     return SDValue();
24345
24346   uint64_t MulAmt1 = 0;
24347   uint64_t MulAmt2 = 0;
24348   if ((MulAmt % 9) == 0) {
24349     MulAmt1 = 9;
24350     MulAmt2 = MulAmt / 9;
24351   } else if ((MulAmt % 5) == 0) {
24352     MulAmt1 = 5;
24353     MulAmt2 = MulAmt / 5;
24354   } else if ((MulAmt % 3) == 0) {
24355     MulAmt1 = 3;
24356     MulAmt2 = MulAmt / 3;
24357   }
24358   if (MulAmt2 &&
24359       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24360     SDLoc DL(N);
24361
24362     if (isPowerOf2_64(MulAmt2) &&
24363         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24364       // If second multiplifer is pow2, issue it first. We want the multiply by
24365       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24366       // is an add.
24367       std::swap(MulAmt1, MulAmt2);
24368
24369     SDValue NewMul;
24370     if (isPowerOf2_64(MulAmt1))
24371       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24372                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
24373     else
24374       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24375                            DAG.getConstant(MulAmt1, VT));
24376
24377     if (isPowerOf2_64(MulAmt2))
24378       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24379                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
24380     else
24381       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24382                            DAG.getConstant(MulAmt2, VT));
24383
24384     // Do not add new nodes to DAG combiner worklist.
24385     DCI.CombineTo(N, NewMul, false);
24386   }
24387   return SDValue();
24388 }
24389
24390 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24391   SDValue N0 = N->getOperand(0);
24392   SDValue N1 = N->getOperand(1);
24393   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24394   EVT VT = N0.getValueType();
24395
24396   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24397   // since the result of setcc_c is all zero's or all ones.
24398   if (VT.isInteger() && !VT.isVector() &&
24399       N1C && N0.getOpcode() == ISD::AND &&
24400       N0.getOperand(1).getOpcode() == ISD::Constant) {
24401     SDValue N00 = N0.getOperand(0);
24402     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
24403         ((N00.getOpcode() == ISD::ANY_EXTEND ||
24404           N00.getOpcode() == ISD::ZERO_EXTEND) &&
24405          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
24406       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24407       APInt ShAmt = N1C->getAPIntValue();
24408       Mask = Mask.shl(ShAmt);
24409       if (Mask != 0)
24410         return DAG.getNode(ISD::AND, SDLoc(N), VT,
24411                            N00, DAG.getConstant(Mask, VT));
24412     }
24413   }
24414
24415   // Hardware support for vector shifts is sparse which makes us scalarize the
24416   // vector operations in many cases. Also, on sandybridge ADD is faster than
24417   // shl.
24418   // (shl V, 1) -> add V,V
24419   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24420     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24421       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24422       // We shift all of the values by one. In many cases we do not have
24423       // hardware support for this operation. This is better expressed as an ADD
24424       // of two values.
24425       if (N1SplatC->getZExtValue() == 1)
24426         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24427     }
24428
24429   return SDValue();
24430 }
24431
24432 /// \brief Returns a vector of 0s if the node in input is a vector logical
24433 /// shift by a constant amount which is known to be bigger than or equal
24434 /// to the vector element size in bits.
24435 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24436                                       const X86Subtarget *Subtarget) {
24437   EVT VT = N->getValueType(0);
24438
24439   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24440       (!Subtarget->hasInt256() ||
24441        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24442     return SDValue();
24443
24444   SDValue Amt = N->getOperand(1);
24445   SDLoc DL(N);
24446   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24447     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24448       APInt ShiftAmt = AmtSplat->getAPIntValue();
24449       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24450
24451       // SSE2/AVX2 logical shifts always return a vector of 0s
24452       // if the shift amount is bigger than or equal to
24453       // the element size. The constant shift amount will be
24454       // encoded as a 8-bit immediate.
24455       if (ShiftAmt.trunc(8).uge(MaxAmount))
24456         return getZeroVector(VT, Subtarget, DAG, DL);
24457     }
24458
24459   return SDValue();
24460 }
24461
24462 /// PerformShiftCombine - Combine shifts.
24463 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24464                                    TargetLowering::DAGCombinerInfo &DCI,
24465                                    const X86Subtarget *Subtarget) {
24466   if (N->getOpcode() == ISD::SHL) {
24467     SDValue V = PerformSHLCombine(N, DAG);
24468     if (V.getNode()) return V;
24469   }
24470
24471   if (N->getOpcode() != ISD::SRA) {
24472     // Try to fold this logical shift into a zero vector.
24473     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
24474     if (V.getNode()) return V;
24475   }
24476
24477   return SDValue();
24478 }
24479
24480 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24481 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24482 // and friends.  Likewise for OR -> CMPNEQSS.
24483 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24484                             TargetLowering::DAGCombinerInfo &DCI,
24485                             const X86Subtarget *Subtarget) {
24486   unsigned opcode;
24487
24488   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24489   // we're requiring SSE2 for both.
24490   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24491     SDValue N0 = N->getOperand(0);
24492     SDValue N1 = N->getOperand(1);
24493     SDValue CMP0 = N0->getOperand(1);
24494     SDValue CMP1 = N1->getOperand(1);
24495     SDLoc DL(N);
24496
24497     // The SETCCs should both refer to the same CMP.
24498     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24499       return SDValue();
24500
24501     SDValue CMP00 = CMP0->getOperand(0);
24502     SDValue CMP01 = CMP0->getOperand(1);
24503     EVT     VT    = CMP00.getValueType();
24504
24505     if (VT == MVT::f32 || VT == MVT::f64) {
24506       bool ExpectingFlags = false;
24507       // Check for any users that want flags:
24508       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24509            !ExpectingFlags && UI != UE; ++UI)
24510         switch (UI->getOpcode()) {
24511         default:
24512         case ISD::BR_CC:
24513         case ISD::BRCOND:
24514         case ISD::SELECT:
24515           ExpectingFlags = true;
24516           break;
24517         case ISD::CopyToReg:
24518         case ISD::SIGN_EXTEND:
24519         case ISD::ZERO_EXTEND:
24520         case ISD::ANY_EXTEND:
24521           break;
24522         }
24523
24524       if (!ExpectingFlags) {
24525         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24526         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24527
24528         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24529           X86::CondCode tmp = cc0;
24530           cc0 = cc1;
24531           cc1 = tmp;
24532         }
24533
24534         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24535             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24536           // FIXME: need symbolic constants for these magic numbers.
24537           // See X86ATTInstPrinter.cpp:printSSECC().
24538           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24539           if (Subtarget->hasAVX512()) {
24540             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24541                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
24542             if (N->getValueType(0) != MVT::i1)
24543               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24544                                  FSetCC);
24545             return FSetCC;
24546           }
24547           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24548                                               CMP00.getValueType(), CMP00, CMP01,
24549                                               DAG.getConstant(x86cc, MVT::i8));
24550
24551           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24552           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24553
24554           if (is64BitFP && !Subtarget->is64Bit()) {
24555             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24556             // 64-bit integer, since that's not a legal type. Since
24557             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24558             // bits, but can do this little dance to extract the lowest 32 bits
24559             // and work with those going forward.
24560             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24561                                            OnesOrZeroesF);
24562             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
24563                                            Vector64);
24564             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24565                                         Vector32, DAG.getIntPtrConstant(0));
24566             IntVT = MVT::i32;
24567           }
24568
24569           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
24570           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24571                                       DAG.getConstant(1, IntVT));
24572           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
24573           return OneBitOfTruth;
24574         }
24575       }
24576     }
24577   }
24578   return SDValue();
24579 }
24580
24581 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24582 /// so it can be folded inside ANDNP.
24583 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24584   EVT VT = N->getValueType(0);
24585
24586   // Match direct AllOnes for 128 and 256-bit vectors
24587   if (ISD::isBuildVectorAllOnes(N))
24588     return true;
24589
24590   // Look through a bit convert.
24591   if (N->getOpcode() == ISD::BITCAST)
24592     N = N->getOperand(0).getNode();
24593
24594   // Sometimes the operand may come from a insert_subvector building a 256-bit
24595   // allones vector
24596   if (VT.is256BitVector() &&
24597       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24598     SDValue V1 = N->getOperand(0);
24599     SDValue V2 = N->getOperand(1);
24600
24601     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24602         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24603         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24604         ISD::isBuildVectorAllOnes(V2.getNode()))
24605       return true;
24606   }
24607
24608   return false;
24609 }
24610
24611 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24612 // register. In most cases we actually compare or select YMM-sized registers
24613 // and mixing the two types creates horrible code. This method optimizes
24614 // some of the transition sequences.
24615 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24616                                  TargetLowering::DAGCombinerInfo &DCI,
24617                                  const X86Subtarget *Subtarget) {
24618   EVT VT = N->getValueType(0);
24619   if (!VT.is256BitVector())
24620     return SDValue();
24621
24622   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24623           N->getOpcode() == ISD::ZERO_EXTEND ||
24624           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24625
24626   SDValue Narrow = N->getOperand(0);
24627   EVT NarrowVT = Narrow->getValueType(0);
24628   if (!NarrowVT.is128BitVector())
24629     return SDValue();
24630
24631   if (Narrow->getOpcode() != ISD::XOR &&
24632       Narrow->getOpcode() != ISD::AND &&
24633       Narrow->getOpcode() != ISD::OR)
24634     return SDValue();
24635
24636   SDValue N0  = Narrow->getOperand(0);
24637   SDValue N1  = Narrow->getOperand(1);
24638   SDLoc DL(Narrow);
24639
24640   // The Left side has to be a trunc.
24641   if (N0.getOpcode() != ISD::TRUNCATE)
24642     return SDValue();
24643
24644   // The type of the truncated inputs.
24645   EVT WideVT = N0->getOperand(0)->getValueType(0);
24646   if (WideVT != VT)
24647     return SDValue();
24648
24649   // The right side has to be a 'trunc' or a constant vector.
24650   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24651   ConstantSDNode *RHSConstSplat = nullptr;
24652   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24653     RHSConstSplat = RHSBV->getConstantSplatNode();
24654   if (!RHSTrunc && !RHSConstSplat)
24655     return SDValue();
24656
24657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24658
24659   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24660     return SDValue();
24661
24662   // Set N0 and N1 to hold the inputs to the new wide operation.
24663   N0 = N0->getOperand(0);
24664   if (RHSConstSplat) {
24665     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24666                      SDValue(RHSConstSplat, 0));
24667     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24668     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24669   } else if (RHSTrunc) {
24670     N1 = N1->getOperand(0);
24671   }
24672
24673   // Generate the wide operation.
24674   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24675   unsigned Opcode = N->getOpcode();
24676   switch (Opcode) {
24677   case ISD::ANY_EXTEND:
24678     return Op;
24679   case ISD::ZERO_EXTEND: {
24680     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24681     APInt Mask = APInt::getAllOnesValue(InBits);
24682     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24683     return DAG.getNode(ISD::AND, DL, VT,
24684                        Op, DAG.getConstant(Mask, VT));
24685   }
24686   case ISD::SIGN_EXTEND:
24687     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24688                        Op, DAG.getValueType(NarrowVT));
24689   default:
24690     llvm_unreachable("Unexpected opcode");
24691   }
24692 }
24693
24694 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24695                                  TargetLowering::DAGCombinerInfo &DCI,
24696                                  const X86Subtarget *Subtarget) {
24697   EVT VT = N->getValueType(0);
24698   if (DCI.isBeforeLegalizeOps())
24699     return SDValue();
24700
24701   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24702   if (R.getNode())
24703     return R;
24704
24705   // Create BEXTR instructions
24706   // BEXTR is ((X >> imm) & (2**size-1))
24707   if (VT == MVT::i32 || VT == MVT::i64) {
24708     SDValue N0 = N->getOperand(0);
24709     SDValue N1 = N->getOperand(1);
24710     SDLoc DL(N);
24711
24712     // Check for BEXTR.
24713     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24714         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24715       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24716       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24717       if (MaskNode && ShiftNode) {
24718         uint64_t Mask = MaskNode->getZExtValue();
24719         uint64_t Shift = ShiftNode->getZExtValue();
24720         if (isMask_64(Mask)) {
24721           uint64_t MaskSize = countPopulation(Mask);
24722           if (Shift + MaskSize <= VT.getSizeInBits())
24723             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24724                                DAG.getConstant(Shift | (MaskSize << 8), VT));
24725         }
24726       }
24727     } // BEXTR
24728
24729     return SDValue();
24730   }
24731
24732   // Want to form ANDNP nodes:
24733   // 1) In the hopes of then easily combining them with OR and AND nodes
24734   //    to form PBLEND/PSIGN.
24735   // 2) To match ANDN packed intrinsics
24736   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24737     return SDValue();
24738
24739   SDValue N0 = N->getOperand(0);
24740   SDValue N1 = N->getOperand(1);
24741   SDLoc DL(N);
24742
24743   // Check LHS for vnot
24744   if (N0.getOpcode() == ISD::XOR &&
24745       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24746       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24747     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24748
24749   // Check RHS for vnot
24750   if (N1.getOpcode() == ISD::XOR &&
24751       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24752       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24753     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24754
24755   return SDValue();
24756 }
24757
24758 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24759                                 TargetLowering::DAGCombinerInfo &DCI,
24760                                 const X86Subtarget *Subtarget) {
24761   if (DCI.isBeforeLegalizeOps())
24762     return SDValue();
24763
24764   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24765   if (R.getNode())
24766     return R;
24767
24768   SDValue N0 = N->getOperand(0);
24769   SDValue N1 = N->getOperand(1);
24770   EVT VT = N->getValueType(0);
24771
24772   // look for psign/blend
24773   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24774     if (!Subtarget->hasSSSE3() ||
24775         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24776       return SDValue();
24777
24778     // Canonicalize pandn to RHS
24779     if (N0.getOpcode() == X86ISD::ANDNP)
24780       std::swap(N0, N1);
24781     // or (and (m, y), (pandn m, x))
24782     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24783       SDValue Mask = N1.getOperand(0);
24784       SDValue X    = N1.getOperand(1);
24785       SDValue Y;
24786       if (N0.getOperand(0) == Mask)
24787         Y = N0.getOperand(1);
24788       if (N0.getOperand(1) == Mask)
24789         Y = N0.getOperand(0);
24790
24791       // Check to see if the mask appeared in both the AND and ANDNP and
24792       if (!Y.getNode())
24793         return SDValue();
24794
24795       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24796       // Look through mask bitcast.
24797       if (Mask.getOpcode() == ISD::BITCAST)
24798         Mask = Mask.getOperand(0);
24799       if (X.getOpcode() == ISD::BITCAST)
24800         X = X.getOperand(0);
24801       if (Y.getOpcode() == ISD::BITCAST)
24802         Y = Y.getOperand(0);
24803
24804       EVT MaskVT = Mask.getValueType();
24805
24806       // Validate that the Mask operand is a vector sra node.
24807       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24808       // there is no psrai.b
24809       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24810       unsigned SraAmt = ~0;
24811       if (Mask.getOpcode() == ISD::SRA) {
24812         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24813           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24814             SraAmt = AmtConst->getZExtValue();
24815       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24816         SDValue SraC = Mask.getOperand(1);
24817         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24818       }
24819       if ((SraAmt + 1) != EltBits)
24820         return SDValue();
24821
24822       SDLoc DL(N);
24823
24824       // Now we know we at least have a plendvb with the mask val.  See if
24825       // we can form a psignb/w/d.
24826       // psign = x.type == y.type == mask.type && y = sub(0, x);
24827       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24828           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24829           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24830         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24831                "Unsupported VT for PSIGN");
24832         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24833         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24834       }
24835       // PBLENDVB only available on SSE 4.1
24836       if (!Subtarget->hasSSE41())
24837         return SDValue();
24838
24839       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24840
24841       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
24842       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
24843       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
24844       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24845       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24846     }
24847   }
24848
24849   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24850     return SDValue();
24851
24852   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24853   MachineFunction &MF = DAG.getMachineFunction();
24854   bool OptForSize =
24855       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
24856
24857   // SHLD/SHRD instructions have lower register pressure, but on some
24858   // platforms they have higher latency than the equivalent
24859   // series of shifts/or that would otherwise be generated.
24860   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24861   // have higher latencies and we are not optimizing for size.
24862   if (!OptForSize && Subtarget->isSHLDSlow())
24863     return SDValue();
24864
24865   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24866     std::swap(N0, N1);
24867   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24868     return SDValue();
24869   if (!N0.hasOneUse() || !N1.hasOneUse())
24870     return SDValue();
24871
24872   SDValue ShAmt0 = N0.getOperand(1);
24873   if (ShAmt0.getValueType() != MVT::i8)
24874     return SDValue();
24875   SDValue ShAmt1 = N1.getOperand(1);
24876   if (ShAmt1.getValueType() != MVT::i8)
24877     return SDValue();
24878   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24879     ShAmt0 = ShAmt0.getOperand(0);
24880   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24881     ShAmt1 = ShAmt1.getOperand(0);
24882
24883   SDLoc DL(N);
24884   unsigned Opc = X86ISD::SHLD;
24885   SDValue Op0 = N0.getOperand(0);
24886   SDValue Op1 = N1.getOperand(0);
24887   if (ShAmt0.getOpcode() == ISD::SUB) {
24888     Opc = X86ISD::SHRD;
24889     std::swap(Op0, Op1);
24890     std::swap(ShAmt0, ShAmt1);
24891   }
24892
24893   unsigned Bits = VT.getSizeInBits();
24894   if (ShAmt1.getOpcode() == ISD::SUB) {
24895     SDValue Sum = ShAmt1.getOperand(0);
24896     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24897       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24898       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24899         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24900       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24901         return DAG.getNode(Opc, DL, VT,
24902                            Op0, Op1,
24903                            DAG.getNode(ISD::TRUNCATE, DL,
24904                                        MVT::i8, ShAmt0));
24905     }
24906   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24907     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24908     if (ShAmt0C &&
24909         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24910       return DAG.getNode(Opc, DL, VT,
24911                          N0.getOperand(0), N1.getOperand(0),
24912                          DAG.getNode(ISD::TRUNCATE, DL,
24913                                        MVT::i8, ShAmt0));
24914   }
24915
24916   return SDValue();
24917 }
24918
24919 // Generate NEG and CMOV for integer abs.
24920 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24921   EVT VT = N->getValueType(0);
24922
24923   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24924   // 8-bit integer abs to NEG and CMOV.
24925   if (VT.isInteger() && VT.getSizeInBits() == 8)
24926     return SDValue();
24927
24928   SDValue N0 = N->getOperand(0);
24929   SDValue N1 = N->getOperand(1);
24930   SDLoc DL(N);
24931
24932   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24933   // and change it to SUB and CMOV.
24934   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24935       N0.getOpcode() == ISD::ADD &&
24936       N0.getOperand(1) == N1 &&
24937       N1.getOpcode() == ISD::SRA &&
24938       N1.getOperand(0) == N0.getOperand(0))
24939     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24940       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24941         // Generate SUB & CMOV.
24942         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24943                                   DAG.getConstant(0, VT), N0.getOperand(0));
24944
24945         SDValue Ops[] = { N0.getOperand(0), Neg,
24946                           DAG.getConstant(X86::COND_GE, MVT::i8),
24947                           SDValue(Neg.getNode(), 1) };
24948         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24949       }
24950   return SDValue();
24951 }
24952
24953 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24954 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24955                                  TargetLowering::DAGCombinerInfo &DCI,
24956                                  const X86Subtarget *Subtarget) {
24957   if (DCI.isBeforeLegalizeOps())
24958     return SDValue();
24959
24960   if (Subtarget->hasCMov()) {
24961     SDValue RV = performIntegerAbsCombine(N, DAG);
24962     if (RV.getNode())
24963       return RV;
24964   }
24965
24966   return SDValue();
24967 }
24968
24969 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24970 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24971                                   TargetLowering::DAGCombinerInfo &DCI,
24972                                   const X86Subtarget *Subtarget) {
24973   LoadSDNode *Ld = cast<LoadSDNode>(N);
24974   EVT RegVT = Ld->getValueType(0);
24975   EVT MemVT = Ld->getMemoryVT();
24976   SDLoc dl(Ld);
24977   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24978
24979   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24980   // into two 16-byte operations.
24981   ISD::LoadExtType Ext = Ld->getExtensionType();
24982   unsigned Alignment = Ld->getAlignment();
24983   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24984   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24985       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24986     unsigned NumElems = RegVT.getVectorNumElements();
24987     if (NumElems < 2)
24988       return SDValue();
24989
24990     SDValue Ptr = Ld->getBasePtr();
24991     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
24992
24993     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24994                                   NumElems/2);
24995     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24996                                 Ld->getPointerInfo(), Ld->isVolatile(),
24997                                 Ld->isNonTemporal(), Ld->isInvariant(),
24998                                 Alignment);
24999     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25000     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25001                                 Ld->getPointerInfo(), Ld->isVolatile(),
25002                                 Ld->isNonTemporal(), Ld->isInvariant(),
25003                                 std::min(16U, Alignment));
25004     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25005                              Load1.getValue(1),
25006                              Load2.getValue(1));
25007
25008     SDValue NewVec = DAG.getUNDEF(RegVT);
25009     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25010     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25011     return DCI.CombineTo(N, NewVec, TF, true);
25012   }
25013
25014   return SDValue();
25015 }
25016
25017 /// PerformMLOADCombine - Resolve extending loads
25018 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25019                                    TargetLowering::DAGCombinerInfo &DCI,
25020                                    const X86Subtarget *Subtarget) {
25021   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25022   if (Mld->getExtensionType() != ISD::SEXTLOAD)
25023     return SDValue();
25024
25025   EVT VT = Mld->getValueType(0);
25026   unsigned NumElems = VT.getVectorNumElements();
25027   EVT LdVT = Mld->getMemoryVT();
25028   SDLoc dl(Mld);
25029
25030   assert(LdVT != VT && "Cannot extend to the same type");
25031   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25032   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25033   // From, To sizes and ElemCount must be pow of two
25034   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25035     "Unexpected size for extending masked load");
25036
25037   unsigned SizeRatio  = ToSz / FromSz;
25038   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25039
25040   // Create a type on which we perform the shuffle
25041   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25042           LdVT.getScalarType(), NumElems*SizeRatio);
25043   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25044
25045   // Convert Src0 value
25046   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
25047   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25048     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25049     for (unsigned i = 0; i != NumElems; ++i)
25050       ShuffleVec[i] = i * SizeRatio;
25051
25052     // Can't shuffle using an illegal type.
25053     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
25054             && "WideVecVT should be legal");
25055     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25056                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25057   }
25058   // Prepare the new mask
25059   SDValue NewMask;
25060   SDValue Mask = Mld->getMask();
25061   if (Mask.getValueType() == VT) {
25062     // Mask and original value have the same type
25063     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
25064     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25065     for (unsigned i = 0; i != NumElems; ++i)
25066       ShuffleVec[i] = i * SizeRatio;
25067     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25068       ShuffleVec[i] = NumElems*SizeRatio;
25069     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25070                                    DAG.getConstant(0, WideVecVT),
25071                                    &ShuffleVec[0]);
25072   }
25073   else {
25074     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25075     unsigned WidenNumElts = NumElems*SizeRatio;
25076     unsigned MaskNumElts = VT.getVectorNumElements();
25077     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25078                                      WidenNumElts);
25079
25080     unsigned NumConcat = WidenNumElts / MaskNumElts;
25081     SmallVector<SDValue, 16> Ops(NumConcat);
25082     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
25083     Ops[0] = Mask;
25084     for (unsigned i = 1; i != NumConcat; ++i)
25085       Ops[i] = ZeroVal;
25086
25087     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25088   }
25089
25090   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25091                                      Mld->getBasePtr(), NewMask, WideSrc0,
25092                                      Mld->getMemoryVT(), Mld->getMemOperand(),
25093                                      ISD::NON_EXTLOAD);
25094   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25095   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25096
25097 }
25098 /// PerformMSTORECombine - Resolve truncating stores
25099 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25100                                     const X86Subtarget *Subtarget) {
25101   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25102   if (!Mst->isTruncatingStore())
25103     return SDValue();
25104
25105   EVT VT = Mst->getValue().getValueType();
25106   unsigned NumElems = VT.getVectorNumElements();
25107   EVT StVT = Mst->getMemoryVT();
25108   SDLoc dl(Mst);
25109
25110   assert(StVT != VT && "Cannot truncate to the same type");
25111   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25112   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25113
25114   // From, To sizes and ElemCount must be pow of two
25115   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25116     "Unexpected size for truncating masked store");
25117   // We are going to use the original vector elt for storing.
25118   // Accumulated smaller vector elements must be a multiple of the store size.
25119   assert (((NumElems * FromSz) % ToSz) == 0 &&
25120           "Unexpected ratio for truncating masked store");
25121
25122   unsigned SizeRatio  = FromSz / ToSz;
25123   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25124
25125   // Create a type on which we perform the shuffle
25126   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25127           StVT.getScalarType(), NumElems*SizeRatio);
25128
25129   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25130
25131   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
25132   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25133   for (unsigned i = 0; i != NumElems; ++i)
25134     ShuffleVec[i] = i * SizeRatio;
25135
25136   // Can't shuffle using an illegal type.
25137   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
25138           && "WideVecVT should be legal");
25139
25140   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25141                                         DAG.getUNDEF(WideVecVT),
25142                                         &ShuffleVec[0]);
25143
25144   SDValue NewMask;
25145   SDValue Mask = Mst->getMask();
25146   if (Mask.getValueType() == VT) {
25147     // Mask and original value have the same type
25148     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
25149     for (unsigned i = 0; i != NumElems; ++i)
25150       ShuffleVec[i] = i * SizeRatio;
25151     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25152       ShuffleVec[i] = NumElems*SizeRatio;
25153     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25154                                    DAG.getConstant(0, WideVecVT),
25155                                    &ShuffleVec[0]);
25156   }
25157   else {
25158     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25159     unsigned WidenNumElts = NumElems*SizeRatio;
25160     unsigned MaskNumElts = VT.getVectorNumElements();
25161     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25162                                      WidenNumElts);
25163
25164     unsigned NumConcat = WidenNumElts / MaskNumElts;
25165     SmallVector<SDValue, 16> Ops(NumConcat);
25166     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
25167     Ops[0] = Mask;
25168     for (unsigned i = 1; i != NumConcat; ++i)
25169       Ops[i] = ZeroVal;
25170
25171     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25172   }
25173
25174   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25175                             NewMask, StVT, Mst->getMemOperand(), false);
25176 }
25177 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25178 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25179                                    const X86Subtarget *Subtarget) {
25180   StoreSDNode *St = cast<StoreSDNode>(N);
25181   EVT VT = St->getValue().getValueType();
25182   EVT StVT = St->getMemoryVT();
25183   SDLoc dl(St);
25184   SDValue StoredVal = St->getOperand(1);
25185   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25186
25187   // If we are saving a concatenation of two XMM registers and 32-byte stores
25188   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25189   unsigned Alignment = St->getAlignment();
25190   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
25191   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
25192       StVT == VT && !IsAligned) {
25193     unsigned NumElems = VT.getVectorNumElements();
25194     if (NumElems < 2)
25195       return SDValue();
25196
25197     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25198     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25199
25200     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
25201     SDValue Ptr0 = St->getBasePtr();
25202     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25203
25204     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25205                                 St->getPointerInfo(), St->isVolatile(),
25206                                 St->isNonTemporal(), Alignment);
25207     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25208                                 St->getPointerInfo(), St->isVolatile(),
25209                                 St->isNonTemporal(),
25210                                 std::min(16U, Alignment));
25211     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25212   }
25213
25214   // Optimize trunc store (of multiple scalars) to shuffle and store.
25215   // First, pack all of the elements in one place. Next, store to memory
25216   // in fewer chunks.
25217   if (St->isTruncatingStore() && VT.isVector()) {
25218     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25219     unsigned NumElems = VT.getVectorNumElements();
25220     assert(StVT != VT && "Cannot truncate to the same type");
25221     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25222     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25223
25224     // From, To sizes and ElemCount must be pow of two
25225     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25226     // We are going to use the original vector elt for storing.
25227     // Accumulated smaller vector elements must be a multiple of the store size.
25228     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25229
25230     unsigned SizeRatio  = FromSz / ToSz;
25231
25232     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25233
25234     // Create a type on which we perform the shuffle
25235     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25236             StVT.getScalarType(), NumElems*SizeRatio);
25237
25238     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25239
25240     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
25241     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25242     for (unsigned i = 0; i != NumElems; ++i)
25243       ShuffleVec[i] = i * SizeRatio;
25244
25245     // Can't shuffle using an illegal type.
25246     if (!TLI.isTypeLegal(WideVecVT))
25247       return SDValue();
25248
25249     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25250                                          DAG.getUNDEF(WideVecVT),
25251                                          &ShuffleVec[0]);
25252     // At this point all of the data is stored at the bottom of the
25253     // register. We now need to save it to mem.
25254
25255     // Find the largest store unit
25256     MVT StoreType = MVT::i8;
25257     for (MVT Tp : MVT::integer_valuetypes()) {
25258       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25259         StoreType = Tp;
25260     }
25261
25262     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25263     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25264         (64 <= NumElems * ToSz))
25265       StoreType = MVT::f64;
25266
25267     // Bitcast the original vector into a vector of store-size units
25268     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25269             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25270     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25271     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
25272     SmallVector<SDValue, 8> Chains;
25273     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
25274                                         TLI.getPointerTy());
25275     SDValue Ptr = St->getBasePtr();
25276
25277     // Perform one or more big stores into memory.
25278     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25279       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25280                                    StoreType, ShuffWide,
25281                                    DAG.getIntPtrConstant(i));
25282       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25283                                 St->getPointerInfo(), St->isVolatile(),
25284                                 St->isNonTemporal(), St->getAlignment());
25285       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25286       Chains.push_back(Ch);
25287     }
25288
25289     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25290   }
25291
25292   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25293   // the FP state in cases where an emms may be missing.
25294   // A preferable solution to the general problem is to figure out the right
25295   // places to insert EMMS.  This qualifies as a quick hack.
25296
25297   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25298   if (VT.getSizeInBits() != 64)
25299     return SDValue();
25300
25301   const Function *F = DAG.getMachineFunction().getFunction();
25302   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25303   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
25304                      && Subtarget->hasSSE2();
25305   if ((VT.isVector() ||
25306        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25307       isa<LoadSDNode>(St->getValue()) &&
25308       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25309       St->getChain().hasOneUse() && !St->isVolatile()) {
25310     SDNode* LdVal = St->getValue().getNode();
25311     LoadSDNode *Ld = nullptr;
25312     int TokenFactorIndex = -1;
25313     SmallVector<SDValue, 8> Ops;
25314     SDNode* ChainVal = St->getChain().getNode();
25315     // Must be a store of a load.  We currently handle two cases:  the load
25316     // is a direct child, and it's under an intervening TokenFactor.  It is
25317     // possible to dig deeper under nested TokenFactors.
25318     if (ChainVal == LdVal)
25319       Ld = cast<LoadSDNode>(St->getChain());
25320     else if (St->getValue().hasOneUse() &&
25321              ChainVal->getOpcode() == ISD::TokenFactor) {
25322       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25323         if (ChainVal->getOperand(i).getNode() == LdVal) {
25324           TokenFactorIndex = i;
25325           Ld = cast<LoadSDNode>(St->getValue());
25326         } else
25327           Ops.push_back(ChainVal->getOperand(i));
25328       }
25329     }
25330
25331     if (!Ld || !ISD::isNormalLoad(Ld))
25332       return SDValue();
25333
25334     // If this is not the MMX case, i.e. we are just turning i64 load/store
25335     // into f64 load/store, avoid the transformation if there are multiple
25336     // uses of the loaded value.
25337     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25338       return SDValue();
25339
25340     SDLoc LdDL(Ld);
25341     SDLoc StDL(N);
25342     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25343     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25344     // pair instead.
25345     if (Subtarget->is64Bit() || F64IsLegal) {
25346       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25347       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25348                                   Ld->getPointerInfo(), Ld->isVolatile(),
25349                                   Ld->isNonTemporal(), Ld->isInvariant(),
25350                                   Ld->getAlignment());
25351       SDValue NewChain = NewLd.getValue(1);
25352       if (TokenFactorIndex != -1) {
25353         Ops.push_back(NewChain);
25354         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25355       }
25356       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25357                           St->getPointerInfo(),
25358                           St->isVolatile(), St->isNonTemporal(),
25359                           St->getAlignment());
25360     }
25361
25362     // Otherwise, lower to two pairs of 32-bit loads / stores.
25363     SDValue LoAddr = Ld->getBasePtr();
25364     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25365                                  DAG.getConstant(4, MVT::i32));
25366
25367     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25368                                Ld->getPointerInfo(),
25369                                Ld->isVolatile(), Ld->isNonTemporal(),
25370                                Ld->isInvariant(), Ld->getAlignment());
25371     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25372                                Ld->getPointerInfo().getWithOffset(4),
25373                                Ld->isVolatile(), Ld->isNonTemporal(),
25374                                Ld->isInvariant(),
25375                                MinAlign(Ld->getAlignment(), 4));
25376
25377     SDValue NewChain = LoLd.getValue(1);
25378     if (TokenFactorIndex != -1) {
25379       Ops.push_back(LoLd);
25380       Ops.push_back(HiLd);
25381       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25382     }
25383
25384     LoAddr = St->getBasePtr();
25385     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25386                          DAG.getConstant(4, MVT::i32));
25387
25388     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25389                                 St->getPointerInfo(),
25390                                 St->isVolatile(), St->isNonTemporal(),
25391                                 St->getAlignment());
25392     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25393                                 St->getPointerInfo().getWithOffset(4),
25394                                 St->isVolatile(),
25395                                 St->isNonTemporal(),
25396                                 MinAlign(St->getAlignment(), 4));
25397     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25398   }
25399   return SDValue();
25400 }
25401
25402 /// Return 'true' if this vector operation is "horizontal"
25403 /// and return the operands for the horizontal operation in LHS and RHS.  A
25404 /// horizontal operation performs the binary operation on successive elements
25405 /// of its first operand, then on successive elements of its second operand,
25406 /// returning the resulting values in a vector.  For example, if
25407 ///   A = < float a0, float a1, float a2, float a3 >
25408 /// and
25409 ///   B = < float b0, float b1, float b2, float b3 >
25410 /// then the result of doing a horizontal operation on A and B is
25411 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25412 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25413 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25414 /// set to A, RHS to B, and the routine returns 'true'.
25415 /// Note that the binary operation should have the property that if one of the
25416 /// operands is UNDEF then the result is UNDEF.
25417 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25418   // Look for the following pattern: if
25419   //   A = < float a0, float a1, float a2, float a3 >
25420   //   B = < float b0, float b1, float b2, float b3 >
25421   // and
25422   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25423   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25424   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25425   // which is A horizontal-op B.
25426
25427   // At least one of the operands should be a vector shuffle.
25428   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25429       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25430     return false;
25431
25432   MVT VT = LHS.getSimpleValueType();
25433
25434   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25435          "Unsupported vector type for horizontal add/sub");
25436
25437   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25438   // operate independently on 128-bit lanes.
25439   unsigned NumElts = VT.getVectorNumElements();
25440   unsigned NumLanes = VT.getSizeInBits()/128;
25441   unsigned NumLaneElts = NumElts / NumLanes;
25442   assert((NumLaneElts % 2 == 0) &&
25443          "Vector type should have an even number of elements in each lane");
25444   unsigned HalfLaneElts = NumLaneElts/2;
25445
25446   // View LHS in the form
25447   //   LHS = VECTOR_SHUFFLE A, B, LMask
25448   // If LHS is not a shuffle then pretend it is the shuffle
25449   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25450   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25451   // type VT.
25452   SDValue A, B;
25453   SmallVector<int, 16> LMask(NumElts);
25454   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25455     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25456       A = LHS.getOperand(0);
25457     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25458       B = LHS.getOperand(1);
25459     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25460     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25461   } else {
25462     if (LHS.getOpcode() != ISD::UNDEF)
25463       A = LHS;
25464     for (unsigned i = 0; i != NumElts; ++i)
25465       LMask[i] = i;
25466   }
25467
25468   // Likewise, view RHS in the form
25469   //   RHS = VECTOR_SHUFFLE C, D, RMask
25470   SDValue C, D;
25471   SmallVector<int, 16> RMask(NumElts);
25472   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25473     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25474       C = RHS.getOperand(0);
25475     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25476       D = RHS.getOperand(1);
25477     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25478     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25479   } else {
25480     if (RHS.getOpcode() != ISD::UNDEF)
25481       C = RHS;
25482     for (unsigned i = 0; i != NumElts; ++i)
25483       RMask[i] = i;
25484   }
25485
25486   // Check that the shuffles are both shuffling the same vectors.
25487   if (!(A == C && B == D) && !(A == D && B == C))
25488     return false;
25489
25490   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25491   if (!A.getNode() && !B.getNode())
25492     return false;
25493
25494   // If A and B occur in reverse order in RHS, then "swap" them (which means
25495   // rewriting the mask).
25496   if (A != C)
25497     CommuteVectorShuffleMask(RMask, NumElts);
25498
25499   // At this point LHS and RHS are equivalent to
25500   //   LHS = VECTOR_SHUFFLE A, B, LMask
25501   //   RHS = VECTOR_SHUFFLE A, B, RMask
25502   // Check that the masks correspond to performing a horizontal operation.
25503   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25504     for (unsigned i = 0; i != NumLaneElts; ++i) {
25505       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25506
25507       // Ignore any UNDEF components.
25508       if (LIdx < 0 || RIdx < 0 ||
25509           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25510           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25511         continue;
25512
25513       // Check that successive elements are being operated on.  If not, this is
25514       // not a horizontal operation.
25515       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25516       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25517       if (!(LIdx == Index && RIdx == Index + 1) &&
25518           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25519         return false;
25520     }
25521   }
25522
25523   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25524   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25525   return true;
25526 }
25527
25528 /// Do target-specific dag combines on floating point adds.
25529 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25530                                   const X86Subtarget *Subtarget) {
25531   EVT VT = N->getValueType(0);
25532   SDValue LHS = N->getOperand(0);
25533   SDValue RHS = N->getOperand(1);
25534
25535   // Try to synthesize horizontal adds from adds of shuffles.
25536   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25537        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25538       isHorizontalBinOp(LHS, RHS, true))
25539     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25540   return SDValue();
25541 }
25542
25543 /// Do target-specific dag combines on floating point subs.
25544 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25545                                   const X86Subtarget *Subtarget) {
25546   EVT VT = N->getValueType(0);
25547   SDValue LHS = N->getOperand(0);
25548   SDValue RHS = N->getOperand(1);
25549
25550   // Try to synthesize horizontal subs from subs of shuffles.
25551   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25552        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25553       isHorizontalBinOp(LHS, RHS, false))
25554     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25555   return SDValue();
25556 }
25557
25558 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25559 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
25560   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25561
25562   // F[X]OR(0.0, x) -> x
25563   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25564     if (C->getValueAPF().isPosZero())
25565       return N->getOperand(1);
25566
25567   // F[X]OR(x, 0.0) -> x
25568   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25569     if (C->getValueAPF().isPosZero())
25570       return N->getOperand(0);
25571   return SDValue();
25572 }
25573
25574 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25575 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25576   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25577
25578   // Only perform optimizations if UnsafeMath is used.
25579   if (!DAG.getTarget().Options.UnsafeFPMath)
25580     return SDValue();
25581
25582   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25583   // into FMINC and FMAXC, which are Commutative operations.
25584   unsigned NewOp = 0;
25585   switch (N->getOpcode()) {
25586     default: llvm_unreachable("unknown opcode");
25587     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25588     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25589   }
25590
25591   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25592                      N->getOperand(0), N->getOperand(1));
25593 }
25594
25595 /// Do target-specific dag combines on X86ISD::FAND nodes.
25596 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25597   // FAND(0.0, x) -> 0.0
25598   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25599     if (C->getValueAPF().isPosZero())
25600       return N->getOperand(0);
25601
25602   // FAND(x, 0.0) -> 0.0
25603   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25604     if (C->getValueAPF().isPosZero())
25605       return N->getOperand(1);
25606   
25607   return SDValue();
25608 }
25609
25610 /// Do target-specific dag combines on X86ISD::FANDN nodes
25611 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25612   // FANDN(0.0, x) -> x
25613   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25614     if (C->getValueAPF().isPosZero())
25615       return N->getOperand(1);
25616
25617   // FANDN(x, 0.0) -> 0.0
25618   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25619     if (C->getValueAPF().isPosZero())
25620       return N->getOperand(1);
25621
25622   return SDValue();
25623 }
25624
25625 static SDValue PerformBTCombine(SDNode *N,
25626                                 SelectionDAG &DAG,
25627                                 TargetLowering::DAGCombinerInfo &DCI) {
25628   // BT ignores high bits in the bit index operand.
25629   SDValue Op1 = N->getOperand(1);
25630   if (Op1.hasOneUse()) {
25631     unsigned BitWidth = Op1.getValueSizeInBits();
25632     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25633     APInt KnownZero, KnownOne;
25634     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25635                                           !DCI.isBeforeLegalizeOps());
25636     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25637     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25638         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25639       DCI.CommitTargetLoweringOpt(TLO);
25640   }
25641   return SDValue();
25642 }
25643
25644 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25645   SDValue Op = N->getOperand(0);
25646   if (Op.getOpcode() == ISD::BITCAST)
25647     Op = Op.getOperand(0);
25648   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25649   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25650       VT.getVectorElementType().getSizeInBits() ==
25651       OpVT.getVectorElementType().getSizeInBits()) {
25652     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25653   }
25654   return SDValue();
25655 }
25656
25657 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25658                                                const X86Subtarget *Subtarget) {
25659   EVT VT = N->getValueType(0);
25660   if (!VT.isVector())
25661     return SDValue();
25662
25663   SDValue N0 = N->getOperand(0);
25664   SDValue N1 = N->getOperand(1);
25665   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25666   SDLoc dl(N);
25667
25668   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25669   // both SSE and AVX2 since there is no sign-extended shift right
25670   // operation on a vector with 64-bit elements.
25671   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25672   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25673   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25674       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25675     SDValue N00 = N0.getOperand(0);
25676
25677     // EXTLOAD has a better solution on AVX2,
25678     // it may be replaced with X86ISD::VSEXT node.
25679     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25680       if (!ISD::isNormalLoad(N00.getNode()))
25681         return SDValue();
25682
25683     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25684         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25685                                   N00, N1);
25686       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25687     }
25688   }
25689   return SDValue();
25690 }
25691
25692 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25693                                   TargetLowering::DAGCombinerInfo &DCI,
25694                                   const X86Subtarget *Subtarget) {
25695   SDValue N0 = N->getOperand(0);
25696   EVT VT = N->getValueType(0);
25697
25698   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25699   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25700   // This exposes the sext to the sdivrem lowering, so that it directly extends
25701   // from AH (which we otherwise need to do contortions to access).
25702   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25703       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
25704     SDLoc dl(N);
25705     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25706     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
25707                             N0.getOperand(0), N0.getOperand(1));
25708     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25709     return R.getValue(1);
25710   }
25711
25712   if (!DCI.isBeforeLegalizeOps())
25713     return SDValue();
25714
25715   if (!Subtarget->hasFp256())
25716     return SDValue();
25717
25718   if (VT.isVector() && VT.getSizeInBits() == 256) {
25719     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25720     if (R.getNode())
25721       return R;
25722   }
25723
25724   return SDValue();
25725 }
25726
25727 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25728                                  const X86Subtarget* Subtarget) {
25729   SDLoc dl(N);
25730   EVT VT = N->getValueType(0);
25731
25732   // Let legalize expand this if it isn't a legal type yet.
25733   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25734     return SDValue();
25735
25736   EVT ScalarVT = VT.getScalarType();
25737   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25738       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
25739     return SDValue();
25740
25741   SDValue A = N->getOperand(0);
25742   SDValue B = N->getOperand(1);
25743   SDValue C = N->getOperand(2);
25744
25745   bool NegA = (A.getOpcode() == ISD::FNEG);
25746   bool NegB = (B.getOpcode() == ISD::FNEG);
25747   bool NegC = (C.getOpcode() == ISD::FNEG);
25748
25749   // Negative multiplication when NegA xor NegB
25750   bool NegMul = (NegA != NegB);
25751   if (NegA)
25752     A = A.getOperand(0);
25753   if (NegB)
25754     B = B.getOperand(0);
25755   if (NegC)
25756     C = C.getOperand(0);
25757
25758   unsigned Opcode;
25759   if (!NegMul)
25760     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25761   else
25762     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25763
25764   return DAG.getNode(Opcode, dl, VT, A, B, C);
25765 }
25766
25767 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25768                                   TargetLowering::DAGCombinerInfo &DCI,
25769                                   const X86Subtarget *Subtarget) {
25770   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25771   //           (and (i32 x86isd::setcc_carry), 1)
25772   // This eliminates the zext. This transformation is necessary because
25773   // ISD::SETCC is always legalized to i8.
25774   SDLoc dl(N);
25775   SDValue N0 = N->getOperand(0);
25776   EVT VT = N->getValueType(0);
25777
25778   if (N0.getOpcode() == ISD::AND &&
25779       N0.hasOneUse() &&
25780       N0.getOperand(0).hasOneUse()) {
25781     SDValue N00 = N0.getOperand(0);
25782     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25783       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25784       if (!C || C->getZExtValue() != 1)
25785         return SDValue();
25786       return DAG.getNode(ISD::AND, dl, VT,
25787                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25788                                      N00.getOperand(0), N00.getOperand(1)),
25789                          DAG.getConstant(1, VT));
25790     }
25791   }
25792
25793   if (N0.getOpcode() == ISD::TRUNCATE &&
25794       N0.hasOneUse() &&
25795       N0.getOperand(0).hasOneUse()) {
25796     SDValue N00 = N0.getOperand(0);
25797     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25798       return DAG.getNode(ISD::AND, dl, VT,
25799                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25800                                      N00.getOperand(0), N00.getOperand(1)),
25801                          DAG.getConstant(1, VT));
25802     }
25803   }
25804   if (VT.is256BitVector()) {
25805     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25806     if (R.getNode())
25807       return R;
25808   }
25809
25810   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25811   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25812   // This exposes the zext to the udivrem lowering, so that it directly extends
25813   // from AH (which we otherwise need to do contortions to access).
25814   if (N0.getOpcode() == ISD::UDIVREM &&
25815       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25816       (VT == MVT::i32 || VT == MVT::i64)) {
25817     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25818     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25819                             N0.getOperand(0), N0.getOperand(1));
25820     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25821     return R.getValue(1);
25822   }
25823
25824   return SDValue();
25825 }
25826
25827 // Optimize x == -y --> x+y == 0
25828 //          x != -y --> x+y != 0
25829 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25830                                       const X86Subtarget* Subtarget) {
25831   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25832   SDValue LHS = N->getOperand(0);
25833   SDValue RHS = N->getOperand(1);
25834   EVT VT = N->getValueType(0);
25835   SDLoc DL(N);
25836
25837   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25838     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25839       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25840         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25841                                    LHS.getValueType(), RHS, LHS.getOperand(1));
25842         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25843                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25844       }
25845   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25846     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25847       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25848         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25849                                    RHS.getValueType(), LHS, RHS.getOperand(1));
25850         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25851                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25852       }
25853
25854   if (VT.getScalarType() == MVT::i1) {
25855     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25856       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25857     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
25858     if (!IsSEXT0 && !IsVZero0)
25859       return SDValue();
25860     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
25861       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25862     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25863
25864     if (!IsSEXT1 && !IsVZero1)
25865       return SDValue();
25866
25867     if (IsSEXT0 && IsVZero1) {
25868       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
25869       if (CC == ISD::SETEQ)
25870         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25871       return LHS.getOperand(0);
25872     }
25873     if (IsSEXT1 && IsVZero0) {
25874       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
25875       if (CC == ISD::SETEQ)
25876         return DAG.getNOT(DL, RHS.getOperand(0), VT);
25877       return RHS.getOperand(0);
25878     }
25879   }
25880
25881   return SDValue();
25882 }
25883
25884 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25885                                       const X86Subtarget *Subtarget) {
25886   SDLoc dl(N);
25887   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25888   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25889          "X86insertps is only defined for v4x32");
25890
25891   SDValue Ld = N->getOperand(1);
25892   if (MayFoldLoad(Ld)) {
25893     // Extract the countS bits from the immediate so we can get the proper
25894     // address when narrowing the vector load to a specific element.
25895     // When the second source op is a memory address, interps doesn't use
25896     // countS and just gets an f32 from that address.
25897     unsigned DestIndex =
25898         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25899     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25900   } else
25901     return SDValue();
25902
25903   // Create this as a scalar to vector to match the instruction pattern.
25904   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25905   // countS bits are ignored when loading from memory on insertps, which
25906   // means we don't need to explicitly set them to 0.
25907   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25908                      LoadScalarToVector, N->getOperand(2));
25909 }
25910
25911 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25912 // as "sbb reg,reg", since it can be extended without zext and produces
25913 // an all-ones bit which is more useful than 0/1 in some cases.
25914 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25915                                MVT VT) {
25916   if (VT == MVT::i8)
25917     return DAG.getNode(ISD::AND, DL, VT,
25918                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25919                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
25920                        DAG.getConstant(1, VT));
25921   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25922   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25923                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25924                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
25925 }
25926
25927 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25928 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25929                                    TargetLowering::DAGCombinerInfo &DCI,
25930                                    const X86Subtarget *Subtarget) {
25931   SDLoc DL(N);
25932   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25933   SDValue EFLAGS = N->getOperand(1);
25934
25935   if (CC == X86::COND_A) {
25936     // Try to convert COND_A into COND_B in an attempt to facilitate
25937     // materializing "setb reg".
25938     //
25939     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25940     // cannot take an immediate as its first operand.
25941     //
25942     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25943         EFLAGS.getValueType().isInteger() &&
25944         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25945       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25946                                    EFLAGS.getNode()->getVTList(),
25947                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25948       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25949       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25950     }
25951   }
25952
25953   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25954   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25955   // cases.
25956   if (CC == X86::COND_B)
25957     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25958
25959   SDValue Flags;
25960
25961   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25962   if (Flags.getNode()) {
25963     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25964     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25965   }
25966
25967   return SDValue();
25968 }
25969
25970 // Optimize branch condition evaluation.
25971 //
25972 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25973                                     TargetLowering::DAGCombinerInfo &DCI,
25974                                     const X86Subtarget *Subtarget) {
25975   SDLoc DL(N);
25976   SDValue Chain = N->getOperand(0);
25977   SDValue Dest = N->getOperand(1);
25978   SDValue EFLAGS = N->getOperand(3);
25979   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25980
25981   SDValue Flags;
25982
25983   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25984   if (Flags.getNode()) {
25985     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25986     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25987                        Flags);
25988   }
25989
25990   return SDValue();
25991 }
25992
25993 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25994                                                          SelectionDAG &DAG) {
25995   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25996   // optimize away operation when it's from a constant.
25997   //
25998   // The general transformation is:
25999   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26000   //       AND(VECTOR_CMP(x,y), constant2)
26001   //    constant2 = UNARYOP(constant)
26002
26003   // Early exit if this isn't a vector operation, the operand of the
26004   // unary operation isn't a bitwise AND, or if the sizes of the operations
26005   // aren't the same.
26006   EVT VT = N->getValueType(0);
26007   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26008       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26009       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26010     return SDValue();
26011
26012   // Now check that the other operand of the AND is a constant. We could
26013   // make the transformation for non-constant splats as well, but it's unclear
26014   // that would be a benefit as it would not eliminate any operations, just
26015   // perform one more step in scalar code before moving to the vector unit.
26016   if (BuildVectorSDNode *BV =
26017           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26018     // Bail out if the vector isn't a constant.
26019     if (!BV->isConstant())
26020       return SDValue();
26021
26022     // Everything checks out. Build up the new and improved node.
26023     SDLoc DL(N);
26024     EVT IntVT = BV->getValueType(0);
26025     // Create a new constant of the appropriate type for the transformed
26026     // DAG.
26027     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26028     // The AND node needs bitcasts to/from an integer vector type around it.
26029     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
26030     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26031                                  N->getOperand(0)->getOperand(0), MaskConst);
26032     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
26033     return Res;
26034   }
26035
26036   return SDValue();
26037 }
26038
26039 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26040                                         const X86Subtarget *Subtarget) {
26041   // First try to optimize away the conversion entirely when it's
26042   // conditionally from a constant. Vectors only.
26043   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
26044   if (Res != SDValue())
26045     return Res;
26046
26047   // Now move on to more general possibilities.
26048   SDValue Op0 = N->getOperand(0);
26049   EVT InVT = Op0->getValueType(0);
26050
26051   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
26052   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
26053     SDLoc dl(N);
26054     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
26055     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26056     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
26057   }
26058
26059   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26060   // a 32-bit target where SSE doesn't support i64->FP operations.
26061   if (Op0.getOpcode() == ISD::LOAD) {
26062     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26063     EVT VT = Ld->getValueType(0);
26064     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
26065         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26066         !Subtarget->is64Bit() && VT == MVT::i64) {
26067       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26068           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
26069       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26070       return FILDChain;
26071     }
26072   }
26073   return SDValue();
26074 }
26075
26076 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26077 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26078                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26079   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26080   // the result is either zero or one (depending on the input carry bit).
26081   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26082   if (X86::isZeroNode(N->getOperand(0)) &&
26083       X86::isZeroNode(N->getOperand(1)) &&
26084       // We don't have a good way to replace an EFLAGS use, so only do this when
26085       // dead right now.
26086       SDValue(N, 1).use_empty()) {
26087     SDLoc DL(N);
26088     EVT VT = N->getValueType(0);
26089     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
26090     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26091                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26092                                            DAG.getConstant(X86::COND_B,MVT::i8),
26093                                            N->getOperand(2)),
26094                                DAG.getConstant(1, VT));
26095     return DCI.CombineTo(N, Res1, CarryOut);
26096   }
26097
26098   return SDValue();
26099 }
26100
26101 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26102 //      (add Y, (setne X, 0)) -> sbb -1, Y
26103 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26104 //      (sub (setne X, 0), Y) -> adc -1, Y
26105 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26106   SDLoc DL(N);
26107
26108   // Look through ZExts.
26109   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26110   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26111     return SDValue();
26112
26113   SDValue SetCC = Ext.getOperand(0);
26114   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26115     return SDValue();
26116
26117   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26118   if (CC != X86::COND_E && CC != X86::COND_NE)
26119     return SDValue();
26120
26121   SDValue Cmp = SetCC.getOperand(1);
26122   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26123       !X86::isZeroNode(Cmp.getOperand(1)) ||
26124       !Cmp.getOperand(0).getValueType().isInteger())
26125     return SDValue();
26126
26127   SDValue CmpOp0 = Cmp.getOperand(0);
26128   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26129                                DAG.getConstant(1, CmpOp0.getValueType()));
26130
26131   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26132   if (CC == X86::COND_NE)
26133     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26134                        DL, OtherVal.getValueType(), OtherVal,
26135                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
26136   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26137                      DL, OtherVal.getValueType(), OtherVal,
26138                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
26139 }
26140
26141 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26142 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26143                                  const X86Subtarget *Subtarget) {
26144   EVT VT = N->getValueType(0);
26145   SDValue Op0 = N->getOperand(0);
26146   SDValue Op1 = N->getOperand(1);
26147
26148   // Try to synthesize horizontal adds from adds of shuffles.
26149   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26150        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26151       isHorizontalBinOp(Op0, Op1, true))
26152     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26153
26154   return OptimizeConditionalInDecrement(N, DAG);
26155 }
26156
26157 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26158                                  const X86Subtarget *Subtarget) {
26159   SDValue Op0 = N->getOperand(0);
26160   SDValue Op1 = N->getOperand(1);
26161
26162   // X86 can't encode an immediate LHS of a sub. See if we can push the
26163   // negation into a preceding instruction.
26164   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26165     // If the RHS of the sub is a XOR with one use and a constant, invert the
26166     // immediate. Then add one to the LHS of the sub so we can turn
26167     // X-Y -> X+~Y+1, saving one register.
26168     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26169         isa<ConstantSDNode>(Op1.getOperand(1))) {
26170       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26171       EVT VT = Op0.getValueType();
26172       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26173                                    Op1.getOperand(0),
26174                                    DAG.getConstant(~XorC, VT));
26175       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26176                          DAG.getConstant(C->getAPIntValue()+1, VT));
26177     }
26178   }
26179
26180   // Try to synthesize horizontal adds from adds of shuffles.
26181   EVT VT = N->getValueType(0);
26182   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26183        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26184       isHorizontalBinOp(Op0, Op1, true))
26185     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26186
26187   return OptimizeConditionalInDecrement(N, DAG);
26188 }
26189
26190 /// performVZEXTCombine - Performs build vector combines
26191 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26192                                    TargetLowering::DAGCombinerInfo &DCI,
26193                                    const X86Subtarget *Subtarget) {
26194   SDLoc DL(N);
26195   MVT VT = N->getSimpleValueType(0);
26196   SDValue Op = N->getOperand(0);
26197   MVT OpVT = Op.getSimpleValueType();
26198   MVT OpEltVT = OpVT.getVectorElementType();
26199   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26200
26201   // (vzext (bitcast (vzext (x)) -> (vzext x)
26202   SDValue V = Op;
26203   while (V.getOpcode() == ISD::BITCAST)
26204     V = V.getOperand(0);
26205
26206   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26207     MVT InnerVT = V.getSimpleValueType();
26208     MVT InnerEltVT = InnerVT.getVectorElementType();
26209
26210     // If the element sizes match exactly, we can just do one larger vzext. This
26211     // is always an exact type match as vzext operates on integer types.
26212     if (OpEltVT == InnerEltVT) {
26213       assert(OpVT == InnerVT && "Types must match for vzext!");
26214       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26215     }
26216
26217     // The only other way we can combine them is if only a single element of the
26218     // inner vzext is used in the input to the outer vzext.
26219     if (InnerEltVT.getSizeInBits() < InputBits)
26220       return SDValue();
26221
26222     // In this case, the inner vzext is completely dead because we're going to
26223     // only look at bits inside of the low element. Just do the outer vzext on
26224     // a bitcast of the input to the inner.
26225     return DAG.getNode(X86ISD::VZEXT, DL, VT,
26226                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
26227   }
26228
26229   // Check if we can bypass extracting and re-inserting an element of an input
26230   // vector. Essentialy:
26231   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26232   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26233       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26234       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26235     SDValue ExtractedV = V.getOperand(0);
26236     SDValue OrigV = ExtractedV.getOperand(0);
26237     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26238       if (ExtractIdx->getZExtValue() == 0) {
26239         MVT OrigVT = OrigV.getSimpleValueType();
26240         // Extract a subvector if necessary...
26241         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26242           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26243           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26244                                     OrigVT.getVectorNumElements() / Ratio);
26245           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26246                               DAG.getIntPtrConstant(0));
26247         }
26248         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
26249         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26250       }
26251   }
26252
26253   return SDValue();
26254 }
26255
26256 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26257                                              DAGCombinerInfo &DCI) const {
26258   SelectionDAG &DAG = DCI.DAG;
26259   switch (N->getOpcode()) {
26260   default: break;
26261   case ISD::EXTRACT_VECTOR_ELT:
26262     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26263   case ISD::VSELECT:
26264   case ISD::SELECT:
26265   case X86ISD::SHRUNKBLEND:
26266     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26267   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26268   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26269   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26270   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26271   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26272   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26273   case ISD::SHL:
26274   case ISD::SRA:
26275   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26276   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26277   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26278   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26279   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26280   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26281   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26282   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26283   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26284   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26285   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26286   case X86ISD::FXOR:
26287   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
26288   case X86ISD::FMIN:
26289   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26290   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26291   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26292   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26293   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26294   case ISD::ANY_EXTEND:
26295   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26296   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26297   case ISD::SIGN_EXTEND_INREG:
26298     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26299   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
26300   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26301   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26302   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26303   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26304   case X86ISD::SHUFP:       // Handle all target specific shuffles
26305   case X86ISD::PALIGNR:
26306   case X86ISD::UNPCKH:
26307   case X86ISD::UNPCKL:
26308   case X86ISD::MOVHLPS:
26309   case X86ISD::MOVLHPS:
26310   case X86ISD::PSHUFB:
26311   case X86ISD::PSHUFD:
26312   case X86ISD::PSHUFHW:
26313   case X86ISD::PSHUFLW:
26314   case X86ISD::MOVSS:
26315   case X86ISD::MOVSD:
26316   case X86ISD::VPERMILPI:
26317   case X86ISD::VPERM2X128:
26318   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26319   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26320   case ISD::INTRINSIC_WO_CHAIN:
26321     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
26322   case X86ISD::INSERTPS: {
26323     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26324       return PerformINSERTPSCombine(N, DAG, Subtarget);
26325     break;
26326   }
26327   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
26328   }
26329
26330   return SDValue();
26331 }
26332
26333 /// isTypeDesirableForOp - Return true if the target has native support for
26334 /// the specified value type and it is 'desirable' to use the type for the
26335 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26336 /// instruction encodings are longer and some i16 instructions are slow.
26337 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26338   if (!isTypeLegal(VT))
26339     return false;
26340   if (VT != MVT::i16)
26341     return true;
26342
26343   switch (Opc) {
26344   default:
26345     return true;
26346   case ISD::LOAD:
26347   case ISD::SIGN_EXTEND:
26348   case ISD::ZERO_EXTEND:
26349   case ISD::ANY_EXTEND:
26350   case ISD::SHL:
26351   case ISD::SRL:
26352   case ISD::SUB:
26353   case ISD::ADD:
26354   case ISD::MUL:
26355   case ISD::AND:
26356   case ISD::OR:
26357   case ISD::XOR:
26358     return false;
26359   }
26360 }
26361
26362 /// IsDesirableToPromoteOp - This method query the target whether it is
26363 /// beneficial for dag combiner to promote the specified node. If true, it
26364 /// should return the desired promotion type by reference.
26365 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26366   EVT VT = Op.getValueType();
26367   if (VT != MVT::i16)
26368     return false;
26369
26370   bool Promote = false;
26371   bool Commute = false;
26372   switch (Op.getOpcode()) {
26373   default: break;
26374   case ISD::LOAD: {
26375     LoadSDNode *LD = cast<LoadSDNode>(Op);
26376     // If the non-extending load has a single use and it's not live out, then it
26377     // might be folded.
26378     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26379                                                      Op.hasOneUse()*/) {
26380       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26381              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26382         // The only case where we'd want to promote LOAD (rather then it being
26383         // promoted as an operand is when it's only use is liveout.
26384         if (UI->getOpcode() != ISD::CopyToReg)
26385           return false;
26386       }
26387     }
26388     Promote = true;
26389     break;
26390   }
26391   case ISD::SIGN_EXTEND:
26392   case ISD::ZERO_EXTEND:
26393   case ISD::ANY_EXTEND:
26394     Promote = true;
26395     break;
26396   case ISD::SHL:
26397   case ISD::SRL: {
26398     SDValue N0 = Op.getOperand(0);
26399     // Look out for (store (shl (load), x)).
26400     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26401       return false;
26402     Promote = true;
26403     break;
26404   }
26405   case ISD::ADD:
26406   case ISD::MUL:
26407   case ISD::AND:
26408   case ISD::OR:
26409   case ISD::XOR:
26410     Commute = true;
26411     // fallthrough
26412   case ISD::SUB: {
26413     SDValue N0 = Op.getOperand(0);
26414     SDValue N1 = Op.getOperand(1);
26415     if (!Commute && MayFoldLoad(N1))
26416       return false;
26417     // Avoid disabling potential load folding opportunities.
26418     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26419       return false;
26420     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26421       return false;
26422     Promote = true;
26423   }
26424   }
26425
26426   PVT = MVT::i32;
26427   return Promote;
26428 }
26429
26430 //===----------------------------------------------------------------------===//
26431 //                           X86 Inline Assembly Support
26432 //===----------------------------------------------------------------------===//
26433
26434 namespace {
26435   // Helper to match a string separated by whitespace.
26436   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
26437     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
26438
26439     for (unsigned i = 0, e = args.size(); i != e; ++i) {
26440       StringRef piece(*args[i]);
26441       if (!s.startswith(piece)) // Check if the piece matches.
26442         return false;
26443
26444       s = s.substr(piece.size());
26445       StringRef::size_type pos = s.find_first_not_of(" \t");
26446       if (pos == 0) // We matched a prefix.
26447         return false;
26448
26449       s = s.substr(pos);
26450     }
26451
26452     return s.empty();
26453   }
26454   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
26455 }
26456
26457 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26458
26459   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26460     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26461         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26462         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26463
26464       if (AsmPieces.size() == 3)
26465         return true;
26466       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26467         return true;
26468     }
26469   }
26470   return false;
26471 }
26472
26473 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26474   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26475
26476   std::string AsmStr = IA->getAsmString();
26477
26478   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26479   if (!Ty || Ty->getBitWidth() % 16 != 0)
26480     return false;
26481
26482   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26483   SmallVector<StringRef, 4> AsmPieces;
26484   SplitString(AsmStr, AsmPieces, ";\n");
26485
26486   switch (AsmPieces.size()) {
26487   default: return false;
26488   case 1:
26489     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26490     // we will turn this bswap into something that will be lowered to logical
26491     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26492     // lower so don't worry about this.
26493     // bswap $0
26494     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
26495         matchAsm(AsmPieces[0], "bswapl", "$0") ||
26496         matchAsm(AsmPieces[0], "bswapq", "$0") ||
26497         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
26498         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
26499         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
26500       // No need to check constraints, nothing other than the equivalent of
26501       // "=r,0" would be valid here.
26502       return IntrinsicLowering::LowerToByteSwap(CI);
26503     }
26504
26505     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26506     if (CI->getType()->isIntegerTy(16) &&
26507         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26508         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
26509          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
26510       AsmPieces.clear();
26511       const std::string &ConstraintsStr = IA->getConstraintString();
26512       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26513       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26514       if (clobbersFlagRegisters(AsmPieces))
26515         return IntrinsicLowering::LowerToByteSwap(CI);
26516     }
26517     break;
26518   case 3:
26519     if (CI->getType()->isIntegerTy(32) &&
26520         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26521         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
26522         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
26523         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
26524       AsmPieces.clear();
26525       const std::string &ConstraintsStr = IA->getConstraintString();
26526       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26527       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26528       if (clobbersFlagRegisters(AsmPieces))
26529         return IntrinsicLowering::LowerToByteSwap(CI);
26530     }
26531
26532     if (CI->getType()->isIntegerTy(64)) {
26533       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26534       if (Constraints.size() >= 2 &&
26535           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26536           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26537         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26538         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
26539             matchAsm(AsmPieces[1], "bswap", "%edx") &&
26540             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
26541           return IntrinsicLowering::LowerToByteSwap(CI);
26542       }
26543     }
26544     break;
26545   }
26546   return false;
26547 }
26548
26549 /// getConstraintType - Given a constraint letter, return the type of
26550 /// constraint it is for this target.
26551 X86TargetLowering::ConstraintType
26552 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
26553   if (Constraint.size() == 1) {
26554     switch (Constraint[0]) {
26555     case 'R':
26556     case 'q':
26557     case 'Q':
26558     case 'f':
26559     case 't':
26560     case 'u':
26561     case 'y':
26562     case 'x':
26563     case 'Y':
26564     case 'l':
26565       return C_RegisterClass;
26566     case 'a':
26567     case 'b':
26568     case 'c':
26569     case 'd':
26570     case 'S':
26571     case 'D':
26572     case 'A':
26573       return C_Register;
26574     case 'I':
26575     case 'J':
26576     case 'K':
26577     case 'L':
26578     case 'M':
26579     case 'N':
26580     case 'G':
26581     case 'C':
26582     case 'e':
26583     case 'Z':
26584       return C_Other;
26585     default:
26586       break;
26587     }
26588   }
26589   return TargetLowering::getConstraintType(Constraint);
26590 }
26591
26592 /// Examine constraint type and operand type and determine a weight value.
26593 /// This object must already have been set up with the operand type
26594 /// and the current alternative constraint selected.
26595 TargetLowering::ConstraintWeight
26596   X86TargetLowering::getSingleConstraintMatchWeight(
26597     AsmOperandInfo &info, const char *constraint) const {
26598   ConstraintWeight weight = CW_Invalid;
26599   Value *CallOperandVal = info.CallOperandVal;
26600     // If we don't have a value, we can't do a match,
26601     // but allow it at the lowest weight.
26602   if (!CallOperandVal)
26603     return CW_Default;
26604   Type *type = CallOperandVal->getType();
26605   // Look at the constraint type.
26606   switch (*constraint) {
26607   default:
26608     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26609   case 'R':
26610   case 'q':
26611   case 'Q':
26612   case 'a':
26613   case 'b':
26614   case 'c':
26615   case 'd':
26616   case 'S':
26617   case 'D':
26618   case 'A':
26619     if (CallOperandVal->getType()->isIntegerTy())
26620       weight = CW_SpecificReg;
26621     break;
26622   case 'f':
26623   case 't':
26624   case 'u':
26625     if (type->isFloatingPointTy())
26626       weight = CW_SpecificReg;
26627     break;
26628   case 'y':
26629     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26630       weight = CW_SpecificReg;
26631     break;
26632   case 'x':
26633   case 'Y':
26634     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26635         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26636       weight = CW_Register;
26637     break;
26638   case 'I':
26639     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26640       if (C->getZExtValue() <= 31)
26641         weight = CW_Constant;
26642     }
26643     break;
26644   case 'J':
26645     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26646       if (C->getZExtValue() <= 63)
26647         weight = CW_Constant;
26648     }
26649     break;
26650   case 'K':
26651     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26652       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26653         weight = CW_Constant;
26654     }
26655     break;
26656   case 'L':
26657     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26658       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26659         weight = CW_Constant;
26660     }
26661     break;
26662   case 'M':
26663     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26664       if (C->getZExtValue() <= 3)
26665         weight = CW_Constant;
26666     }
26667     break;
26668   case 'N':
26669     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26670       if (C->getZExtValue() <= 0xff)
26671         weight = CW_Constant;
26672     }
26673     break;
26674   case 'G':
26675   case 'C':
26676     if (dyn_cast<ConstantFP>(CallOperandVal)) {
26677       weight = CW_Constant;
26678     }
26679     break;
26680   case 'e':
26681     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26682       if ((C->getSExtValue() >= -0x80000000LL) &&
26683           (C->getSExtValue() <= 0x7fffffffLL))
26684         weight = CW_Constant;
26685     }
26686     break;
26687   case 'Z':
26688     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26689       if (C->getZExtValue() <= 0xffffffff)
26690         weight = CW_Constant;
26691     }
26692     break;
26693   }
26694   return weight;
26695 }
26696
26697 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26698 /// with another that has more specific requirements based on the type of the
26699 /// corresponding operand.
26700 const char *X86TargetLowering::
26701 LowerXConstraint(EVT ConstraintVT) const {
26702   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26703   // 'f' like normal targets.
26704   if (ConstraintVT.isFloatingPoint()) {
26705     if (Subtarget->hasSSE2())
26706       return "Y";
26707     if (Subtarget->hasSSE1())
26708       return "x";
26709   }
26710
26711   return TargetLowering::LowerXConstraint(ConstraintVT);
26712 }
26713
26714 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26715 /// vector.  If it is invalid, don't add anything to Ops.
26716 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26717                                                      std::string &Constraint,
26718                                                      std::vector<SDValue>&Ops,
26719                                                      SelectionDAG &DAG) const {
26720   SDValue Result;
26721
26722   // Only support length 1 constraints for now.
26723   if (Constraint.length() > 1) return;
26724
26725   char ConstraintLetter = Constraint[0];
26726   switch (ConstraintLetter) {
26727   default: break;
26728   case 'I':
26729     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26730       if (C->getZExtValue() <= 31) {
26731         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26732         break;
26733       }
26734     }
26735     return;
26736   case 'J':
26737     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26738       if (C->getZExtValue() <= 63) {
26739         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26740         break;
26741       }
26742     }
26743     return;
26744   case 'K':
26745     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26746       if (isInt<8>(C->getSExtValue())) {
26747         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26748         break;
26749       }
26750     }
26751     return;
26752   case 'L':
26753     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26754       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26755           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26756         Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
26757         break;
26758       }
26759     }
26760     return;
26761   case 'M':
26762     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26763       if (C->getZExtValue() <= 3) {
26764         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26765         break;
26766       }
26767     }
26768     return;
26769   case 'N':
26770     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26771       if (C->getZExtValue() <= 255) {
26772         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26773         break;
26774       }
26775     }
26776     return;
26777   case 'O':
26778     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26779       if (C->getZExtValue() <= 127) {
26780         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26781         break;
26782       }
26783     }
26784     return;
26785   case 'e': {
26786     // 32-bit signed value
26787     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26788       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26789                                            C->getSExtValue())) {
26790         // Widen to 64 bits here to get it sign extended.
26791         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
26792         break;
26793       }
26794     // FIXME gcc accepts some relocatable values here too, but only in certain
26795     // memory models; it's complicated.
26796     }
26797     return;
26798   }
26799   case 'Z': {
26800     // 32-bit unsigned value
26801     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26802       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26803                                            C->getZExtValue())) {
26804         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26805         break;
26806       }
26807     }
26808     // FIXME gcc accepts some relocatable values here too, but only in certain
26809     // memory models; it's complicated.
26810     return;
26811   }
26812   case 'i': {
26813     // Literal immediates are always ok.
26814     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26815       // Widen to 64 bits here to get it sign extended.
26816       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
26817       break;
26818     }
26819
26820     // In any sort of PIC mode addresses need to be computed at runtime by
26821     // adding in a register or some sort of table lookup.  These can't
26822     // be used as immediates.
26823     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26824       return;
26825
26826     // If we are in non-pic codegen mode, we allow the address of a global (with
26827     // an optional displacement) to be used with 'i'.
26828     GlobalAddressSDNode *GA = nullptr;
26829     int64_t Offset = 0;
26830
26831     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26832     while (1) {
26833       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26834         Offset += GA->getOffset();
26835         break;
26836       } else if (Op.getOpcode() == ISD::ADD) {
26837         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26838           Offset += C->getZExtValue();
26839           Op = Op.getOperand(0);
26840           continue;
26841         }
26842       } else if (Op.getOpcode() == ISD::SUB) {
26843         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26844           Offset += -C->getZExtValue();
26845           Op = Op.getOperand(0);
26846           continue;
26847         }
26848       }
26849
26850       // Otherwise, this isn't something we can handle, reject it.
26851       return;
26852     }
26853
26854     const GlobalValue *GV = GA->getGlobal();
26855     // If we require an extra load to get this address, as in PIC mode, we
26856     // can't accept it.
26857     if (isGlobalStubReference(
26858             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26859       return;
26860
26861     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26862                                         GA->getValueType(0), Offset);
26863     break;
26864   }
26865   }
26866
26867   if (Result.getNode()) {
26868     Ops.push_back(Result);
26869     return;
26870   }
26871   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26872 }
26873
26874 std::pair<unsigned, const TargetRegisterClass*>
26875 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
26876                                                 MVT VT) const {
26877   // First, see if this is a constraint that directly corresponds to an LLVM
26878   // register class.
26879   if (Constraint.size() == 1) {
26880     // GCC Constraint Letters
26881     switch (Constraint[0]) {
26882     default: break;
26883       // TODO: Slight differences here in allocation order and leaving
26884       // RIP in the class. Do they matter any more here than they do
26885       // in the normal allocation?
26886     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26887       if (Subtarget->is64Bit()) {
26888         if (VT == MVT::i32 || VT == MVT::f32)
26889           return std::make_pair(0U, &X86::GR32RegClass);
26890         if (VT == MVT::i16)
26891           return std::make_pair(0U, &X86::GR16RegClass);
26892         if (VT == MVT::i8 || VT == MVT::i1)
26893           return std::make_pair(0U, &X86::GR8RegClass);
26894         if (VT == MVT::i64 || VT == MVT::f64)
26895           return std::make_pair(0U, &X86::GR64RegClass);
26896         break;
26897       }
26898       // 32-bit fallthrough
26899     case 'Q':   // Q_REGS
26900       if (VT == MVT::i32 || VT == MVT::f32)
26901         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26902       if (VT == MVT::i16)
26903         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26904       if (VT == MVT::i8 || VT == MVT::i1)
26905         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26906       if (VT == MVT::i64)
26907         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26908       break;
26909     case 'r':   // GENERAL_REGS
26910     case 'l':   // INDEX_REGS
26911       if (VT == MVT::i8 || VT == MVT::i1)
26912         return std::make_pair(0U, &X86::GR8RegClass);
26913       if (VT == MVT::i16)
26914         return std::make_pair(0U, &X86::GR16RegClass);
26915       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26916         return std::make_pair(0U, &X86::GR32RegClass);
26917       return std::make_pair(0U, &X86::GR64RegClass);
26918     case 'R':   // LEGACY_REGS
26919       if (VT == MVT::i8 || VT == MVT::i1)
26920         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26921       if (VT == MVT::i16)
26922         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26923       if (VT == MVT::i32 || !Subtarget->is64Bit())
26924         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26925       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26926     case 'f':  // FP Stack registers.
26927       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26928       // value to the correct fpstack register class.
26929       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26930         return std::make_pair(0U, &X86::RFP32RegClass);
26931       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26932         return std::make_pair(0U, &X86::RFP64RegClass);
26933       return std::make_pair(0U, &X86::RFP80RegClass);
26934     case 'y':   // MMX_REGS if MMX allowed.
26935       if (!Subtarget->hasMMX()) break;
26936       return std::make_pair(0U, &X86::VR64RegClass);
26937     case 'Y':   // SSE_REGS if SSE2 allowed
26938       if (!Subtarget->hasSSE2()) break;
26939       // FALL THROUGH.
26940     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26941       if (!Subtarget->hasSSE1()) break;
26942
26943       switch (VT.SimpleTy) {
26944       default: break;
26945       // Scalar SSE types.
26946       case MVT::f32:
26947       case MVT::i32:
26948         return std::make_pair(0U, &X86::FR32RegClass);
26949       case MVT::f64:
26950       case MVT::i64:
26951         return std::make_pair(0U, &X86::FR64RegClass);
26952       // Vector types.
26953       case MVT::v16i8:
26954       case MVT::v8i16:
26955       case MVT::v4i32:
26956       case MVT::v2i64:
26957       case MVT::v4f32:
26958       case MVT::v2f64:
26959         return std::make_pair(0U, &X86::VR128RegClass);
26960       // AVX types.
26961       case MVT::v32i8:
26962       case MVT::v16i16:
26963       case MVT::v8i32:
26964       case MVT::v4i64:
26965       case MVT::v8f32:
26966       case MVT::v4f64:
26967         return std::make_pair(0U, &X86::VR256RegClass);
26968       case MVT::v8f64:
26969       case MVT::v16f32:
26970       case MVT::v16i32:
26971       case MVT::v8i64:
26972         return std::make_pair(0U, &X86::VR512RegClass);
26973       }
26974       break;
26975     }
26976   }
26977
26978   // Use the default implementation in TargetLowering to convert the register
26979   // constraint into a member of a register class.
26980   std::pair<unsigned, const TargetRegisterClass*> Res;
26981   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
26982
26983   // Not found as a standard register?
26984   if (!Res.second) {
26985     // Map st(0) -> st(7) -> ST0
26986     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26987         tolower(Constraint[1]) == 's' &&
26988         tolower(Constraint[2]) == 't' &&
26989         Constraint[3] == '(' &&
26990         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26991         Constraint[5] == ')' &&
26992         Constraint[6] == '}') {
26993
26994       Res.first = X86::FP0+Constraint[4]-'0';
26995       Res.second = &X86::RFP80RegClass;
26996       return Res;
26997     }
26998
26999     // GCC allows "st(0)" to be called just plain "st".
27000     if (StringRef("{st}").equals_lower(Constraint)) {
27001       Res.first = X86::FP0;
27002       Res.second = &X86::RFP80RegClass;
27003       return Res;
27004     }
27005
27006     // flags -> EFLAGS
27007     if (StringRef("{flags}").equals_lower(Constraint)) {
27008       Res.first = X86::EFLAGS;
27009       Res.second = &X86::CCRRegClass;
27010       return Res;
27011     }
27012
27013     // 'A' means EAX + EDX.
27014     if (Constraint == "A") {
27015       Res.first = X86::EAX;
27016       Res.second = &X86::GR32_ADRegClass;
27017       return Res;
27018     }
27019     return Res;
27020   }
27021
27022   // Otherwise, check to see if this is a register class of the wrong value
27023   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27024   // turn into {ax},{dx}.
27025   if (Res.second->hasType(VT))
27026     return Res;   // Correct type already, nothing to do.
27027
27028   // All of the single-register GCC register classes map their values onto
27029   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
27030   // really want an 8-bit or 32-bit register, map to the appropriate register
27031   // class and return the appropriate register.
27032   if (Res.second == &X86::GR16RegClass) {
27033     if (VT == MVT::i8 || VT == MVT::i1) {
27034       unsigned DestReg = 0;
27035       switch (Res.first) {
27036       default: break;
27037       case X86::AX: DestReg = X86::AL; break;
27038       case X86::DX: DestReg = X86::DL; break;
27039       case X86::CX: DestReg = X86::CL; break;
27040       case X86::BX: DestReg = X86::BL; break;
27041       }
27042       if (DestReg) {
27043         Res.first = DestReg;
27044         Res.second = &X86::GR8RegClass;
27045       }
27046     } else if (VT == MVT::i32 || VT == MVT::f32) {
27047       unsigned DestReg = 0;
27048       switch (Res.first) {
27049       default: break;
27050       case X86::AX: DestReg = X86::EAX; break;
27051       case X86::DX: DestReg = X86::EDX; break;
27052       case X86::CX: DestReg = X86::ECX; break;
27053       case X86::BX: DestReg = X86::EBX; break;
27054       case X86::SI: DestReg = X86::ESI; break;
27055       case X86::DI: DestReg = X86::EDI; break;
27056       case X86::BP: DestReg = X86::EBP; break;
27057       case X86::SP: DestReg = X86::ESP; break;
27058       }
27059       if (DestReg) {
27060         Res.first = DestReg;
27061         Res.second = &X86::GR32RegClass;
27062       }
27063     } else if (VT == MVT::i64 || VT == MVT::f64) {
27064       unsigned DestReg = 0;
27065       switch (Res.first) {
27066       default: break;
27067       case X86::AX: DestReg = X86::RAX; break;
27068       case X86::DX: DestReg = X86::RDX; break;
27069       case X86::CX: DestReg = X86::RCX; break;
27070       case X86::BX: DestReg = X86::RBX; break;
27071       case X86::SI: DestReg = X86::RSI; break;
27072       case X86::DI: DestReg = X86::RDI; break;
27073       case X86::BP: DestReg = X86::RBP; break;
27074       case X86::SP: DestReg = X86::RSP; break;
27075       }
27076       if (DestReg) {
27077         Res.first = DestReg;
27078         Res.second = &X86::GR64RegClass;
27079       }
27080     }
27081   } else if (Res.second == &X86::FR32RegClass ||
27082              Res.second == &X86::FR64RegClass ||
27083              Res.second == &X86::VR128RegClass ||
27084              Res.second == &X86::VR256RegClass ||
27085              Res.second == &X86::FR32XRegClass ||
27086              Res.second == &X86::FR64XRegClass ||
27087              Res.second == &X86::VR128XRegClass ||
27088              Res.second == &X86::VR256XRegClass ||
27089              Res.second == &X86::VR512RegClass) {
27090     // Handle references to XMM physical registers that got mapped into the
27091     // wrong class.  This can happen with constraints like {xmm0} where the
27092     // target independent register mapper will just pick the first match it can
27093     // find, ignoring the required type.
27094
27095     if (VT == MVT::f32 || VT == MVT::i32)
27096       Res.second = &X86::FR32RegClass;
27097     else if (VT == MVT::f64 || VT == MVT::i64)
27098       Res.second = &X86::FR64RegClass;
27099     else if (X86::VR128RegClass.hasType(VT))
27100       Res.second = &X86::VR128RegClass;
27101     else if (X86::VR256RegClass.hasType(VT))
27102       Res.second = &X86::VR256RegClass;
27103     else if (X86::VR512RegClass.hasType(VT))
27104       Res.second = &X86::VR512RegClass;
27105   }
27106
27107   return Res;
27108 }
27109
27110 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
27111                                             Type *Ty) const {
27112   // Scaling factors are not free at all.
27113   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27114   // will take 2 allocations in the out of order engine instead of 1
27115   // for plain addressing mode, i.e. inst (reg1).
27116   // E.g.,
27117   // vaddps (%rsi,%drx), %ymm0, %ymm1
27118   // Requires two allocations (one for the load, one for the computation)
27119   // whereas:
27120   // vaddps (%rsi), %ymm0, %ymm1
27121   // Requires just 1 allocation, i.e., freeing allocations for other operations
27122   // and having less micro operations to execute.
27123   //
27124   // For some X86 architectures, this is even worse because for instance for
27125   // stores, the complex addressing mode forces the instruction to use the
27126   // "load" ports instead of the dedicated "store" port.
27127   // E.g., on Haswell:
27128   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27129   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27130   if (isLegalAddressingMode(AM, Ty))
27131     // Scale represents reg2 * scale, thus account for 1
27132     // as soon as we use a second register.
27133     return AM.Scale != 0;
27134   return -1;
27135 }
27136
27137 bool X86TargetLowering::isTargetFTOL() const {
27138   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
27139 }