[CodeGen] Use MVT iterator_ranges in legality loops. NFC intended.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallBitVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/VariadicFunction.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
54 #include <bitset>
55 #include <numeric>
56 #include <cctype>
57 using namespace llvm;
58
59 #define DEBUG_TYPE "x86-isel"
60
61 STATISTIC(NumTailCalls, "Number of tail calls");
62
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64     "x86-experimental-vector-widening-legalization", cl::init(false),
65     cl::desc("Enable an experimental vector type legalization through widening "
66              "rather than promotion."),
67     cl::Hidden);
68
69 static cl::opt<bool> ExperimentalVectorShuffleLowering(
70     "x86-experimental-vector-shuffle-lowering", cl::init(true),
71     cl::desc("Enable an experimental vector shuffle lowering code path."),
72     cl::Hidden);
73
74 static cl::opt<int> ReciprocalEstimateRefinementSteps(
75     "x86-recip-refinement-steps", cl::init(1),
76     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
77              "result of the hardware reciprocal estimate instruction."),
78     cl::NotHidden);
79
80 // Forward declarations.
81 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
82                        SDValue V2);
83
84 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
85                                 SelectionDAG &DAG, SDLoc dl,
86                                 unsigned vectorWidth) {
87   assert((vectorWidth == 128 || vectorWidth == 256) &&
88          "Unsupported vector width");
89   EVT VT = Vec.getValueType();
90   EVT ElVT = VT.getVectorElementType();
91   unsigned Factor = VT.getSizeInBits()/vectorWidth;
92   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
93                                   VT.getVectorNumElements()/Factor);
94
95   // Extract from UNDEF is UNDEF.
96   if (Vec.getOpcode() == ISD::UNDEF)
97     return DAG.getUNDEF(ResultVT);
98
99   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
100   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
101
102   // This is the index of the first element of the vectorWidth-bit chunk
103   // we want.
104   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
105                                * ElemsPerChunk);
106
107   // If the input is a buildvector just emit a smaller one.
108   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
109     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
110                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
111                                     ElemsPerChunk));
112
113   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
114   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
115 }
116
117 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
118 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
119 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
120 /// instructions or a simple subregister reference. Idx is an index in the
121 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
122 /// lowering EXTRACT_VECTOR_ELT operations easier.
123 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
124                                    SelectionDAG &DAG, SDLoc dl) {
125   assert((Vec.getValueType().is256BitVector() ||
126           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
127   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
128 }
129
130 /// Generate a DAG to grab 256-bits from a 512-bit vector.
131 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
132                                    SelectionDAG &DAG, SDLoc dl) {
133   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
134   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
135 }
136
137 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
138                                unsigned IdxVal, SelectionDAG &DAG,
139                                SDLoc dl, unsigned vectorWidth) {
140   assert((vectorWidth == 128 || vectorWidth == 256) &&
141          "Unsupported vector width");
142   // Inserting UNDEF is Result
143   if (Vec.getOpcode() == ISD::UNDEF)
144     return Result;
145   EVT VT = Vec.getValueType();
146   EVT ElVT = VT.getVectorElementType();
147   EVT ResultVT = Result.getValueType();
148
149   // Insert the relevant vectorWidth bits.
150   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
151
152   // This is the index of the first element of the vectorWidth-bit chunk
153   // we want.
154   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
155                                * ElemsPerChunk);
156
157   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
158   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
159 }
160
161 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
162 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
163 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
164 /// simple superregister reference.  Idx is an index in the 128 bits
165 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
166 /// lowering INSERT_VECTOR_ELT operations easier.
167 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
168                                   SelectionDAG &DAG,SDLoc dl) {
169   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
170   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
171 }
172
173 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
174                                   SelectionDAG &DAG, SDLoc dl) {
175   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
176   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
177 }
178
179 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
180 /// instructions. This is used because creating CONCAT_VECTOR nodes of
181 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
182 /// large BUILD_VECTORS.
183 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
184                                    unsigned NumElems, SelectionDAG &DAG,
185                                    SDLoc dl) {
186   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
187   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
188 }
189
190 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
191                                    unsigned NumElems, SelectionDAG &DAG,
192                                    SDLoc dl) {
193   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
194   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
195 }
196
197 // FIXME: This should stop caching the target machine as soon as
198 // we can remove resetOperationActions et al.
199 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM)
200     : TargetLowering(TM) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird. It always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit, since we have so many registers, use the ILP scheduler.
234   // For 32-bit, use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2.
247   if (TM.getOptLevel() >= CodeGenOpt::Default) {
248     if (Subtarget->hasSlowDivide32())
249       addBypassSlowDiv(32, 8);
250     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
251       addBypassSlowDiv(64, 16);
252   }
253
254   if (Subtarget->isTargetKnownWindowsMSVC()) {
255     // Setup Windows compiler runtime calls.
256     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258     setLibcallName(RTLIB::SREM_I64, "_allrem");
259     setLibcallName(RTLIB::UREM_I64, "_aullrem");
260     setLibcallName(RTLIB::MUL_I64, "_allmul");
261     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266
267     // The _ftol2 runtime function has an unusual calling conv, which
268     // is modeled by a special pseudo-instruction.
269     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
273   }
274
275   if (Subtarget->isTargetDarwin()) {
276     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277     setUseUnderscoreSetJmp(false);
278     setUseUnderscoreLongJmp(false);
279   } else if (Subtarget->isTargetWindowsGNU()) {
280     // MS runtime is weird: it exports _setjmp, but longjmp!
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(false);
283   } else {
284     setUseUnderscoreSetJmp(true);
285     setUseUnderscoreLongJmp(true);
286   }
287
288   // Set up the register classes.
289   addRegisterClass(MVT::i8, &X86::GR8RegClass);
290   addRegisterClass(MVT::i16, &X86::GR16RegClass);
291   addRegisterClass(MVT::i32, &X86::GR32RegClass);
292   if (Subtarget->is64Bit())
293     addRegisterClass(MVT::i64, &X86::GR64RegClass);
294
295   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296
297   // We don't accept any truncstore of integer registers.
298   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
304
305   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
306
307   // SETOEQ and SETUNE require checking two conditions.
308   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314
315   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316   // operation.
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
318   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
319   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
320
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
323     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
324   } else if (!TM.Options.UseSoftFloat) {
325     // We have an algorithm for SSE2->double, and we turn this into a
326     // 64-bit FILD followed by conditional FADD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
328     // We have an algorithm for SSE2, and we turn this into a 64-bit
329     // FILD for other targets.
330     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
331   }
332
333   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
336   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
337
338   if (!TM.Options.UseSoftFloat) {
339     // SSE has no i16 to fp conversion, only i32
340     if (X86ScalarSSEf32) {
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
342       // f32 and f64 cases are Legal, f80 case is not
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     } else {
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
346       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
347     }
348   } else {
349     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
350     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
351   }
352
353   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
354   // are Legal, f80 is custom lowered.
355   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
356   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
357
358   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359   // this operation.
360   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
361   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
362
363   if (X86ScalarSSEf32) {
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
365     // f32 and f64 cases are Legal, f80 case is not
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   } else {
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
369     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
370   }
371
372   // Handle FP_TO_UINT by promoting the destination to a larger signed
373   // conversion.
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
375   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
376   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
377
378   if (Subtarget->is64Bit()) {
379     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
380     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
381   } else if (!TM.Options.UseSoftFloat) {
382     // Since AVX is a superset of SSE3, only check for SSE here.
383     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384       // Expand FP_TO_UINT into a select.
385       // FIXME: We would like to use a Custom expander here eventually to do
386       // the optimal thing for SSE vs. the default expansion in the legalizer.
387       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
388     else
389       // With SSE3 we can use fisttpll to convert to a signed i64; without
390       // SSE, we're stuck with a fistpll.
391       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
392   }
393
394   if (isTargetFTOL()) {
395     // Use the _ftol2 runtime function, which has a pseudo-instruction
396     // to handle its weird calling convention.
397     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
398   }
399
400   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401   if (!X86ScalarSSEf64) {
402     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
403     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
404     if (Subtarget->is64Bit()) {
405       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
406       // Without SSE, i64->f64 goes through memory.
407       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
408     }
409   }
410
411   // Scalar integer divide and remainder are lowered to use operations that
412   // produce two results, to match the available instructions. This exposes
413   // the two-result form to trivial CSE, which is able to combine x/y and x%y
414   // into a single instruction.
415   //
416   // Scalar integer multiply-high is also lowered to use two-result
417   // operations, to match the available instructions. However, plain multiply
418   // (low) operations are left as Legal, as there are single-result
419   // instructions for this in x86. Using the two-result multiply instructions
420   // when both high and low results are needed must be arranged by dagcombine.
421   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422     MVT VT = IntVTs[i];
423     setOperationAction(ISD::MULHS, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::SDIV, VT, Expand);
426     setOperationAction(ISD::UDIV, VT, Expand);
427     setOperationAction(ISD::SREM, VT, Expand);
428     setOperationAction(ISD::UREM, VT, Expand);
429
430     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431     setOperationAction(ISD::ADDC, VT, Custom);
432     setOperationAction(ISD::ADDE, VT, Custom);
433     setOperationAction(ISD::SUBC, VT, Custom);
434     setOperationAction(ISD::SUBE, VT, Custom);
435   }
436
437   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
438   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
439   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
445   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
447   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
448   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
449   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
450   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
451   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
452   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
453   if (Subtarget->is64Bit())
454     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
455   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
456   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
457   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
458   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
459   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
460   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
461   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
462   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
463
464   // Promote the i8 variants and force them on up to i32 which has a shorter
465   // encoding.
466   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
467   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
468   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
469   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
470   if (Subtarget->hasBMI()) {
471     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
472     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
473     if (Subtarget->is64Bit())
474       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
475   } else {
476     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
477     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
478     if (Subtarget->is64Bit())
479       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
480   }
481
482   if (Subtarget->hasLZCNT()) {
483     // When promoting the i8 variants, force them to i32 for a shorter
484     // encoding.
485     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
486     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
488     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
491     if (Subtarget->is64Bit())
492       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
493   } else {
494     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
495     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
496     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
497     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
498     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
500     if (Subtarget->is64Bit()) {
501       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
502       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
503     }
504   }
505
506   // Special handling for half-precision floating point conversions.
507   // If we don't have F16C support, then lower half float conversions
508   // into library calls.
509   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
510     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
511     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
512   }
513
514   // There's never any support for operations beyond MVT::f32.
515   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
516   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
517   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
518   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
519
520   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
521   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
522   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
523   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
524
525   if (Subtarget->hasPOPCNT()) {
526     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
527   } else {
528     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
529     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
530     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
531     if (Subtarget->is64Bit())
532       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
533   }
534
535   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
536
537   if (!Subtarget->hasMOVBE())
538     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
539
540   // These should be promoted to a larger select which is supported.
541   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
542   // X86 wants to expand cmov itself.
543   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
544   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
545   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
546   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
547   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
548   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
549   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
550   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
551   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
552   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
553   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
554   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
555   if (Subtarget->is64Bit()) {
556     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
557     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
558   }
559   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
560   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
561   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
562   // support continuation, user-level threading, and etc.. As a result, no
563   // other SjLj exception interfaces are implemented and please don't build
564   // your own exception handling based on them.
565   // LLVM/Clang supports zero-cost DWARF exception handling.
566   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
567   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
568
569   // Darwin ABI issue.
570   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
571   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
572   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
573   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
574   if (Subtarget->is64Bit())
575     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
576   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
577   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
578   if (Subtarget->is64Bit()) {
579     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
580     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
581     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
582     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
583     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
584   }
585   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
586   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
587   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
588   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
589   if (Subtarget->is64Bit()) {
590     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
591     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
592     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
593   }
594
595   if (Subtarget->hasSSE1())
596     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
597
598   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
599
600   // Expand certain atomics
601   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
602     MVT VT = IntVTs[i];
603     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
604     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
605     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
606   }
607
608   if (Subtarget->hasCmpxchg16b()) {
609     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
610   }
611
612   // FIXME - use subtarget debug flags
613   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
614       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
615     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
616   }
617
618   if (Subtarget->is64Bit()) {
619     setExceptionPointerRegister(X86::RAX);
620     setExceptionSelectorRegister(X86::RDX);
621   } else {
622     setExceptionPointerRegister(X86::EAX);
623     setExceptionSelectorRegister(X86::EDX);
624   }
625   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
626   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
627
628   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
629   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
630
631   setOperationAction(ISD::TRAP, MVT::Other, Legal);
632   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
633
634   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
635   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
636   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
637   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
638     // TargetInfo::X86_64ABIBuiltinVaList
639     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
640     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
641   } else {
642     // TargetInfo::CharPtrBuiltinVaList
643     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
644     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
645   }
646
647   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
648   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
649
650   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
651
652   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
653     // f32 and f64 use SSE.
654     // Set up the FP register classes.
655     addRegisterClass(MVT::f32, &X86::FR32RegClass);
656     addRegisterClass(MVT::f64, &X86::FR64RegClass);
657
658     // Use ANDPD to simulate FABS.
659     setOperationAction(ISD::FABS , MVT::f64, Custom);
660     setOperationAction(ISD::FABS , MVT::f32, Custom);
661
662     // Use XORP to simulate FNEG.
663     setOperationAction(ISD::FNEG , MVT::f64, Custom);
664     setOperationAction(ISD::FNEG , MVT::f32, Custom);
665
666     // Use ANDPD and ORPD to simulate FCOPYSIGN.
667     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
668     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
669
670     // Lower this to FGETSIGNx86 plus an AND.
671     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
672     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
673
674     // We don't support sin/cos/fmod
675     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
676     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
677     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
678     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
679     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
680     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
681
682     // Expand FP immediates into loads from the stack, except for the special
683     // cases we handle.
684     addLegalFPImmediate(APFloat(+0.0)); // xorpd
685     addLegalFPImmediate(APFloat(+0.0f)); // xorps
686   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
687     // Use SSE for f32, x87 for f64.
688     // Set up the FP register classes.
689     addRegisterClass(MVT::f32, &X86::FR32RegClass);
690     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
691
692     // Use ANDPS to simulate FABS.
693     setOperationAction(ISD::FABS , MVT::f32, Custom);
694
695     // Use XORP to simulate FNEG.
696     setOperationAction(ISD::FNEG , MVT::f32, Custom);
697
698     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
699
700     // Use ANDPS and ORPS to simulate FCOPYSIGN.
701     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
702     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
703
704     // We don't support sin/cos/fmod
705     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
706     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
707     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
708
709     // Special cases we handle for FP constants.
710     addLegalFPImmediate(APFloat(+0.0f)); // xorps
711     addLegalFPImmediate(APFloat(+0.0)); // FLD0
712     addLegalFPImmediate(APFloat(+1.0)); // FLD1
713     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
714     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
715
716     if (!TM.Options.UnsafeFPMath) {
717       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
718       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
719       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
720     }
721   } else if (!TM.Options.UseSoftFloat) {
722     // f32 and f64 in x87.
723     // Set up the FP register classes.
724     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
725     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
726
727     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
728     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
729     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
730     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
731
732     if (!TM.Options.UnsafeFPMath) {
733       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
734       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
735       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
736       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
737       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
738       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
739     }
740     addLegalFPImmediate(APFloat(+0.0)); // FLD0
741     addLegalFPImmediate(APFloat(+1.0)); // FLD1
742     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
743     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
744     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
745     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
746     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
747     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
748   }
749
750   // We don't support FMA.
751   setOperationAction(ISD::FMA, MVT::f64, Expand);
752   setOperationAction(ISD::FMA, MVT::f32, Expand);
753
754   // Long double always uses X87.
755   if (!TM.Options.UseSoftFloat) {
756     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
757     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
758     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
759     {
760       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
761       addLegalFPImmediate(TmpFlt);  // FLD0
762       TmpFlt.changeSign();
763       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
764
765       bool ignored;
766       APFloat TmpFlt2(+1.0);
767       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
768                       &ignored);
769       addLegalFPImmediate(TmpFlt2);  // FLD1
770       TmpFlt2.changeSign();
771       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
772     }
773
774     if (!TM.Options.UnsafeFPMath) {
775       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
776       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
777       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
778     }
779
780     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
781     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
782     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
783     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
784     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
785     setOperationAction(ISD::FMA, MVT::f80, Expand);
786   }
787
788   // Always use a library call for pow.
789   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
790   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
791   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
792
793   setOperationAction(ISD::FLOG, MVT::f80, Expand);
794   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
795   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
796   setOperationAction(ISD::FEXP, MVT::f80, Expand);
797   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
798   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
799   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
800
801   // First set operation action for all vector types to either promote
802   // (for widening) or expand (for scalarization). Then we will selectively
803   // turn on ones that can be effectively codegen'd.
804   for (MVT VT : MVT::vector_valuetypes()) {
805     setOperationAction(ISD::ADD , VT, Expand);
806     setOperationAction(ISD::SUB , VT, Expand);
807     setOperationAction(ISD::FADD, VT, Expand);
808     setOperationAction(ISD::FNEG, VT, Expand);
809     setOperationAction(ISD::FSUB, VT, Expand);
810     setOperationAction(ISD::MUL , VT, Expand);
811     setOperationAction(ISD::FMUL, VT, Expand);
812     setOperationAction(ISD::SDIV, VT, Expand);
813     setOperationAction(ISD::UDIV, VT, Expand);
814     setOperationAction(ISD::FDIV, VT, Expand);
815     setOperationAction(ISD::SREM, VT, Expand);
816     setOperationAction(ISD::UREM, VT, Expand);
817     setOperationAction(ISD::LOAD, VT, Expand);
818     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
819     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
820     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
821     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
822     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
823     setOperationAction(ISD::FABS, VT, Expand);
824     setOperationAction(ISD::FSIN, VT, Expand);
825     setOperationAction(ISD::FSINCOS, VT, Expand);
826     setOperationAction(ISD::FCOS, VT, Expand);
827     setOperationAction(ISD::FSINCOS, VT, Expand);
828     setOperationAction(ISD::FREM, VT, Expand);
829     setOperationAction(ISD::FMA,  VT, Expand);
830     setOperationAction(ISD::FPOWI, VT, Expand);
831     setOperationAction(ISD::FSQRT, VT, Expand);
832     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
833     setOperationAction(ISD::FFLOOR, VT, Expand);
834     setOperationAction(ISD::FCEIL, VT, Expand);
835     setOperationAction(ISD::FTRUNC, VT, Expand);
836     setOperationAction(ISD::FRINT, VT, Expand);
837     setOperationAction(ISD::FNEARBYINT, VT, Expand);
838     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
839     setOperationAction(ISD::MULHS, VT, Expand);
840     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
841     setOperationAction(ISD::MULHU, VT, Expand);
842     setOperationAction(ISD::SDIVREM, VT, Expand);
843     setOperationAction(ISD::UDIVREM, VT, Expand);
844     setOperationAction(ISD::FPOW, VT, Expand);
845     setOperationAction(ISD::CTPOP, VT, Expand);
846     setOperationAction(ISD::CTTZ, VT, Expand);
847     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
848     setOperationAction(ISD::CTLZ, VT, Expand);
849     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
850     setOperationAction(ISD::SHL, VT, Expand);
851     setOperationAction(ISD::SRA, VT, Expand);
852     setOperationAction(ISD::SRL, VT, Expand);
853     setOperationAction(ISD::ROTL, VT, Expand);
854     setOperationAction(ISD::ROTR, VT, Expand);
855     setOperationAction(ISD::BSWAP, VT, Expand);
856     setOperationAction(ISD::SETCC, VT, Expand);
857     setOperationAction(ISD::FLOG, VT, Expand);
858     setOperationAction(ISD::FLOG2, VT, Expand);
859     setOperationAction(ISD::FLOG10, VT, Expand);
860     setOperationAction(ISD::FEXP, VT, Expand);
861     setOperationAction(ISD::FEXP2, VT, Expand);
862     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
863     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
864     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
865     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
866     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
867     setOperationAction(ISD::TRUNCATE, VT, Expand);
868     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
869     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
870     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
871     setOperationAction(ISD::VSELECT, VT, Expand);
872     setOperationAction(ISD::SELECT_CC, VT, Expand);
873     for (MVT InnerVT : MVT::vector_valuetypes())
874       setTruncStoreAction(VT, InnerVT, Expand);
875     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
876     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
877
878     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
879     // we have to deal with them whether we ask for Expansion or not. Setting
880     // Expand causes its own optimisation problems though, so leave them legal.
881     if (VT.getVectorElementType() == MVT::i1)
882       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
883   }
884
885   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
886   // with -msoft-float, disable use of MMX as well.
887   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
888     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
889     // No operations on x86mmx supported, everything uses intrinsics.
890   }
891
892   // MMX-sized vectors (other than x86mmx) are expected to be expanded
893   // into smaller operations.
894   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
895   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
896   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
897   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
898   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
899   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
900   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
901   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
902   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
903   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
904   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
905   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
906   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
907   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
908   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
909   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
910   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
911   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
912   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
913   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
914   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
915   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
916   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
917   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
918   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
919   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
920   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
921   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
922   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
923
924   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
925     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
926
927     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
928     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
929     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
930     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
931     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
932     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
933     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
934     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
935     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
936     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
937     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
938     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
939     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
940   }
941
942   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
943     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
944
945     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
946     // registers cannot be used even for integer operations.
947     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
948     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
949     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
950     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
951
952     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
953     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
954     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
955     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
956     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
957     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
958     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
959     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
960     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
961     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
962     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
963     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
964     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
965     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
966     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
967     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
968     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
969     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
970     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
971     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
972     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
973     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
974
975     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
976     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
977     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
978     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
979
980     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
981     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
984     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
985
986     // Only provide customized ctpop vector bit twiddling for vector types we
987     // know to perform better than using the popcnt instructions on each vector
988     // element. If popcnt isn't supported, always provide the custom version.
989     if (!Subtarget->hasPOPCNT()) {
990       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
991       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
992     }
993
994     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
995     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
996       MVT VT = (MVT::SimpleValueType)i;
997       // Do not attempt to custom lower non-power-of-2 vectors
998       if (!isPowerOf2_32(VT.getVectorNumElements()))
999         continue;
1000       // Do not attempt to custom lower non-128-bit vectors
1001       if (!VT.is128BitVector())
1002         continue;
1003       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1004       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1005       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1006     }
1007
1008     // We support custom legalizing of sext and anyext loads for specific
1009     // memory vector types which we can load as a scalar (or sequence of
1010     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1011     // loads these must work with a single scalar load.
1012     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1013     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1014     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1015     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1016     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1017     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1018     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1019     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1020     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1021
1022     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1023     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1024     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1025     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1026     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1027     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1028
1029     if (Subtarget->is64Bit()) {
1030       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1031       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1032     }
1033
1034     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1035     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1036       MVT VT = (MVT::SimpleValueType)i;
1037
1038       // Do not attempt to promote non-128-bit vectors
1039       if (!VT.is128BitVector())
1040         continue;
1041
1042       setOperationAction(ISD::AND,    VT, Promote);
1043       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1044       setOperationAction(ISD::OR,     VT, Promote);
1045       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1046       setOperationAction(ISD::XOR,    VT, Promote);
1047       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1048       setOperationAction(ISD::LOAD,   VT, Promote);
1049       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1050       setOperationAction(ISD::SELECT, VT, Promote);
1051       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1052     }
1053
1054     // Custom lower v2i64 and v2f64 selects.
1055     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1056     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1057     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1058     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1059
1060     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1061     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1062
1063     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1064     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1065     // As there is no 64-bit GPR available, we need build a special custom
1066     // sequence to convert from v2i32 to v2f32.
1067     if (!Subtarget->is64Bit())
1068       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1069
1070     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1071     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1072
1073     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1074
1075     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1076     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1077     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1078   }
1079
1080   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1081     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1082     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1083     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1084     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1085     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1086     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1087     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1088     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1089     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1090     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1091
1092     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1093     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1094     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1095     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1096     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1097     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1098     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1099     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1100     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1101     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1102
1103     // FIXME: Do we need to handle scalar-to-vector here?
1104     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1105
1106     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1107     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1108     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1109     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1110     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1111     // There is no BLENDI for byte vectors. We don't need to custom lower
1112     // some vselects for now.
1113     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1114
1115     // SSE41 brings specific instructions for doing vector sign extend even in
1116     // cases where we don't have SRA.
1117     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1118     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1119     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1120
1121     // i8 and i16 vectors are custom because the source register and source
1122     // source memory operand types are not the same width.  f32 vectors are
1123     // custom since the immediate controlling the insert encodes additional
1124     // information.
1125     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1126     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1127     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1128     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1129
1130     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1131     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1132     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1133     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1134
1135     // FIXME: these should be Legal, but that's only for the case where
1136     // the index is constant.  For now custom expand to deal with that.
1137     if (Subtarget->is64Bit()) {
1138       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1139       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1140     }
1141   }
1142
1143   if (Subtarget->hasSSE2()) {
1144     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1145     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1146
1147     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1148     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1149
1150     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1151     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1152
1153     // In the customized shift lowering, the legal cases in AVX2 will be
1154     // recognized.
1155     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1156     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1157
1158     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1159     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1160
1161     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1162   }
1163
1164   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1165     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1166     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1167     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1168     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1169     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1170     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1171
1172     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1173     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1174     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1175
1176     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1177     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1178     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1179     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1180     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1181     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1182     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1183     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1184     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1185     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1186     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1187     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1188
1189     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1190     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1191     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1192     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1193     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1194     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1195     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1196     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1197     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1198     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1199     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1200     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1201
1202     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1203     // even though v8i16 is a legal type.
1204     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1205     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1206     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1207
1208     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1209     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1210     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1211
1212     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1213     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1214
1215     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1216
1217     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1218     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1219
1220     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1221     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1222
1223     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1224     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1225
1226     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1227     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1228     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1229     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1230
1231     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1232     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1233     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1234
1235     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1236     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1237     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1238     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1239
1240     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1241     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1242     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1243     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1244     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1245     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1246     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1247     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1248     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1249     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1250     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1251     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1252
1253     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1254       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1255       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1256       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1257       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1258       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1259       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1260     }
1261
1262     if (Subtarget->hasInt256()) {
1263       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1264       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1265       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1266       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1267
1268       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1269       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1270       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1271       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1272
1273       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1274       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1275       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1276       // Don't lower v32i8 because there is no 128-bit byte mul
1277
1278       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1279       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1280       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1281       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1282
1283       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1284       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1285
1286       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1287       // when we have a 256bit-wide blend with immediate.
1288       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1289
1290       // Only provide customized ctpop vector bit twiddling for vector types we
1291       // know to perform better than using the popcnt instructions on each
1292       // vector element. If popcnt isn't supported, always provide the custom
1293       // version.
1294       if (!Subtarget->hasPOPCNT())
1295         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1296
1297       // Custom CTPOP always performs better on natively supported v8i32
1298       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1299     } else {
1300       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1301       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1302       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1303       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1304
1305       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1306       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1307       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1308       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1309
1310       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1311       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1312       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1313       // Don't lower v32i8 because there is no 128-bit byte mul
1314     }
1315
1316     // In the customized shift lowering, the legal cases in AVX2 will be
1317     // recognized.
1318     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1319     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1320
1321     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1322     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1323
1324     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1325
1326     // Custom lower several nodes for 256-bit types.
1327     for (MVT VT : MVT::vector_valuetypes()) {
1328       if (VT.getScalarSizeInBits() >= 32) {
1329         setOperationAction(ISD::MLOAD,  VT, Legal);
1330         setOperationAction(ISD::MSTORE, VT, Legal);
1331       }
1332       // Extract subvector is special because the value type
1333       // (result) is 128-bit but the source is 256-bit wide.
1334       if (VT.is128BitVector()) {
1335         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1336       }
1337       // Do not attempt to custom lower other non-256-bit vectors
1338       if (!VT.is256BitVector())
1339         continue;
1340
1341       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1342       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1343       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1344       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1345       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1346       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1347       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1348     }
1349
1350     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1351     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1352       MVT VT = (MVT::SimpleValueType)i;
1353
1354       // Do not attempt to promote non-256-bit vectors
1355       if (!VT.is256BitVector())
1356         continue;
1357
1358       setOperationAction(ISD::AND,    VT, Promote);
1359       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1360       setOperationAction(ISD::OR,     VT, Promote);
1361       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1362       setOperationAction(ISD::XOR,    VT, Promote);
1363       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1364       setOperationAction(ISD::LOAD,   VT, Promote);
1365       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1366       setOperationAction(ISD::SELECT, VT, Promote);
1367       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1368     }
1369   }
1370
1371   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1372     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1373     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1374     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1375     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1376
1377     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1378     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1379     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1380
1381     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1382     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1383     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1384     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1385     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1386     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1387     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1389     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1390     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1391     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1392
1393     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1394     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1395     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1396     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1397     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1398     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1399
1400     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1401     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1402     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1403     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1404     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1405     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1406     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1407     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1408
1409     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1410     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1411     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1412     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1413     if (Subtarget->is64Bit()) {
1414       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1415       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1416       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1417       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1418     }
1419     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1420     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1421     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1422     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1423     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1424     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1425     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1426     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1427     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1428     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1429     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1430     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1431     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1432     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1433
1434     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1435     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1436     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1437     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1438     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1439     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1440     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1441     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1442     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1443     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1444     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1445     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1446     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1447
1448     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1449     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1450     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1451     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1452     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1453     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1454
1455     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1456     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1457
1458     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1459
1460     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1461     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1462     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1463     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1464     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1465     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1466     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1467     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1468     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1469
1470     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1471     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1472
1473     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1474     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1475
1476     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1477
1478     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1479     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1480
1481     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1482     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1483
1484     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1485     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1486
1487     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1488     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1489     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1490     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1491     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1492     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1493
1494     if (Subtarget->hasCDI()) {
1495       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1496       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1497     }
1498
1499     // Custom lower several nodes.
1500     for (MVT VT : MVT::vector_valuetypes()) {
1501       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1502       // Extract subvector is special because the value type
1503       // (result) is 256/128-bit but the source is 512-bit wide.
1504       if (VT.is128BitVector() || VT.is256BitVector()) {
1505         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1506       }
1507       if (VT.getVectorElementType() == MVT::i1)
1508         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1509
1510       // Do not attempt to custom lower other non-512-bit vectors
1511       if (!VT.is512BitVector())
1512         continue;
1513
1514       if ( EltSize >= 32) {
1515         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1516         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1517         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1518         setOperationAction(ISD::VSELECT,             VT, Legal);
1519         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1520         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1521         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1522         setOperationAction(ISD::MLOAD,               VT, Legal);
1523         setOperationAction(ISD::MSTORE,              VT, Legal);
1524       }
1525     }
1526     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1527       MVT VT = (MVT::SimpleValueType)i;
1528
1529       // Do not attempt to promote non-512-bit vectors.
1530       if (!VT.is512BitVector())
1531         continue;
1532
1533       setOperationAction(ISD::SELECT, VT, Promote);
1534       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1535     }
1536   }// has  AVX-512
1537
1538   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1539     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1540     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1541
1542     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1543     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1544
1545     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1546     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1547     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1548     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1549     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1550     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1551     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1552     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1553     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1554
1555     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1556       const MVT VT = (MVT::SimpleValueType)i;
1557
1558       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1559
1560       // Do not attempt to promote non-512-bit vectors.
1561       if (!VT.is512BitVector())
1562         continue;
1563
1564       if (EltSize < 32) {
1565         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1566         setOperationAction(ISD::VSELECT,             VT, Legal);
1567       }
1568     }
1569   }
1570
1571   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1572     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1573     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1574
1575     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1576     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1577     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1578
1579     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1580     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1581     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1582     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1583     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1584     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1585   }
1586
1587   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1588   // of this type with custom code.
1589   for (MVT VT : MVT::vector_valuetypes())
1590     setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1591
1592   // We want to custom lower some of our intrinsics.
1593   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1594   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1595   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1596   if (!Subtarget->is64Bit())
1597     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1598
1599   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1600   // handle type legalization for these operations here.
1601   //
1602   // FIXME: We really should do custom legalization for addition and
1603   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1604   // than generic legalization for 64-bit multiplication-with-overflow, though.
1605   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1606     // Add/Sub/Mul with overflow operations are custom lowered.
1607     MVT VT = IntVTs[i];
1608     setOperationAction(ISD::SADDO, VT, Custom);
1609     setOperationAction(ISD::UADDO, VT, Custom);
1610     setOperationAction(ISD::SSUBO, VT, Custom);
1611     setOperationAction(ISD::USUBO, VT, Custom);
1612     setOperationAction(ISD::SMULO, VT, Custom);
1613     setOperationAction(ISD::UMULO, VT, Custom);
1614   }
1615
1616
1617   if (!Subtarget->is64Bit()) {
1618     // These libcalls are not available in 32-bit.
1619     setLibcallName(RTLIB::SHL_I128, nullptr);
1620     setLibcallName(RTLIB::SRL_I128, nullptr);
1621     setLibcallName(RTLIB::SRA_I128, nullptr);
1622   }
1623
1624   // Combine sin / cos into one node or libcall if possible.
1625   if (Subtarget->hasSinCos()) {
1626     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1627     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1628     if (Subtarget->isTargetDarwin()) {
1629       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1630       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1631       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1632       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1633     }
1634   }
1635
1636   if (Subtarget->isTargetWin64()) {
1637     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1638     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1639     setOperationAction(ISD::SREM, MVT::i128, Custom);
1640     setOperationAction(ISD::UREM, MVT::i128, Custom);
1641     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1642     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1643   }
1644
1645   // We have target-specific dag combine patterns for the following nodes:
1646   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1647   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1648   setTargetDAGCombine(ISD::VSELECT);
1649   setTargetDAGCombine(ISD::SELECT);
1650   setTargetDAGCombine(ISD::SHL);
1651   setTargetDAGCombine(ISD::SRA);
1652   setTargetDAGCombine(ISD::SRL);
1653   setTargetDAGCombine(ISD::OR);
1654   setTargetDAGCombine(ISD::AND);
1655   setTargetDAGCombine(ISD::ADD);
1656   setTargetDAGCombine(ISD::FADD);
1657   setTargetDAGCombine(ISD::FSUB);
1658   setTargetDAGCombine(ISD::FMA);
1659   setTargetDAGCombine(ISD::SUB);
1660   setTargetDAGCombine(ISD::LOAD);
1661   setTargetDAGCombine(ISD::STORE);
1662   setTargetDAGCombine(ISD::ZERO_EXTEND);
1663   setTargetDAGCombine(ISD::ANY_EXTEND);
1664   setTargetDAGCombine(ISD::SIGN_EXTEND);
1665   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1666   setTargetDAGCombine(ISD::TRUNCATE);
1667   setTargetDAGCombine(ISD::SINT_TO_FP);
1668   setTargetDAGCombine(ISD::SETCC);
1669   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1670   setTargetDAGCombine(ISD::BUILD_VECTOR);
1671   if (Subtarget->is64Bit())
1672     setTargetDAGCombine(ISD::MUL);
1673   setTargetDAGCombine(ISD::XOR);
1674
1675   computeRegisterProperties();
1676
1677   // On Darwin, -Os means optimize for size without hurting performance,
1678   // do not reduce the limit.
1679   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1680   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1681   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1682   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1683   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1684   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1685   setPrefLoopAlignment(4); // 2^4 bytes.
1686
1687   // Predictable cmov don't hurt on atom because it's in-order.
1688   PredictableSelectIsExpensive = !Subtarget->isAtom();
1689   EnableExtLdPromotion = true;
1690   setPrefFunctionAlignment(4); // 2^4 bytes.
1691
1692   verifyIntrinsicTables();
1693 }
1694
1695 // This has so far only been implemented for 64-bit MachO.
1696 bool X86TargetLowering::useLoadStackGuardNode() const {
1697   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1698 }
1699
1700 TargetLoweringBase::LegalizeTypeAction
1701 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1702   if (ExperimentalVectorWideningLegalization &&
1703       VT.getVectorNumElements() != 1 &&
1704       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1705     return TypeWidenVector;
1706
1707   return TargetLoweringBase::getPreferredVectorAction(VT);
1708 }
1709
1710 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1711   if (!VT.isVector())
1712     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1713
1714   const unsigned NumElts = VT.getVectorNumElements();
1715   const EVT EltVT = VT.getVectorElementType();
1716   if (VT.is512BitVector()) {
1717     if (Subtarget->hasAVX512())
1718       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1719           EltVT == MVT::f32 || EltVT == MVT::f64)
1720         switch(NumElts) {
1721         case  8: return MVT::v8i1;
1722         case 16: return MVT::v16i1;
1723       }
1724     if (Subtarget->hasBWI())
1725       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1726         switch(NumElts) {
1727         case 32: return MVT::v32i1;
1728         case 64: return MVT::v64i1;
1729       }
1730   }
1731
1732   if (VT.is256BitVector() || VT.is128BitVector()) {
1733     if (Subtarget->hasVLX())
1734       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1735           EltVT == MVT::f32 || EltVT == MVT::f64)
1736         switch(NumElts) {
1737         case 2: return MVT::v2i1;
1738         case 4: return MVT::v4i1;
1739         case 8: return MVT::v8i1;
1740       }
1741     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1742       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1743         switch(NumElts) {
1744         case  8: return MVT::v8i1;
1745         case 16: return MVT::v16i1;
1746         case 32: return MVT::v32i1;
1747       }
1748   }
1749
1750   return VT.changeVectorElementTypeToInteger();
1751 }
1752
1753 /// Helper for getByValTypeAlignment to determine
1754 /// the desired ByVal argument alignment.
1755 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1756   if (MaxAlign == 16)
1757     return;
1758   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1759     if (VTy->getBitWidth() == 128)
1760       MaxAlign = 16;
1761   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1762     unsigned EltAlign = 0;
1763     getMaxByValAlign(ATy->getElementType(), EltAlign);
1764     if (EltAlign > MaxAlign)
1765       MaxAlign = EltAlign;
1766   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1767     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1768       unsigned EltAlign = 0;
1769       getMaxByValAlign(STy->getElementType(i), EltAlign);
1770       if (EltAlign > MaxAlign)
1771         MaxAlign = EltAlign;
1772       if (MaxAlign == 16)
1773         break;
1774     }
1775   }
1776 }
1777
1778 /// Return the desired alignment for ByVal aggregate
1779 /// function arguments in the caller parameter area. For X86, aggregates
1780 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1781 /// are at 4-byte boundaries.
1782 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1783   if (Subtarget->is64Bit()) {
1784     // Max of 8 and alignment of type.
1785     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1786     if (TyAlign > 8)
1787       return TyAlign;
1788     return 8;
1789   }
1790
1791   unsigned Align = 4;
1792   if (Subtarget->hasSSE1())
1793     getMaxByValAlign(Ty, Align);
1794   return Align;
1795 }
1796
1797 /// Returns the target specific optimal type for load
1798 /// and store operations as a result of memset, memcpy, and memmove
1799 /// lowering. If DstAlign is zero that means it's safe to destination
1800 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1801 /// means there isn't a need to check it against alignment requirement,
1802 /// probably because the source does not need to be loaded. If 'IsMemset' is
1803 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1804 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1805 /// source is constant so it does not need to be loaded.
1806 /// It returns EVT::Other if the type should be determined using generic
1807 /// target-independent logic.
1808 EVT
1809 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1810                                        unsigned DstAlign, unsigned SrcAlign,
1811                                        bool IsMemset, bool ZeroMemset,
1812                                        bool MemcpyStrSrc,
1813                                        MachineFunction &MF) const {
1814   const Function *F = MF.getFunction();
1815   if ((!IsMemset || ZeroMemset) &&
1816       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1817                                        Attribute::NoImplicitFloat)) {
1818     if (Size >= 16 &&
1819         (Subtarget->isUnalignedMemAccessFast() ||
1820          ((DstAlign == 0 || DstAlign >= 16) &&
1821           (SrcAlign == 0 || SrcAlign >= 16)))) {
1822       if (Size >= 32) {
1823         if (Subtarget->hasInt256())
1824           return MVT::v8i32;
1825         if (Subtarget->hasFp256())
1826           return MVT::v8f32;
1827       }
1828       if (Subtarget->hasSSE2())
1829         return MVT::v4i32;
1830       if (Subtarget->hasSSE1())
1831         return MVT::v4f32;
1832     } else if (!MemcpyStrSrc && Size >= 8 &&
1833                !Subtarget->is64Bit() &&
1834                Subtarget->hasSSE2()) {
1835       // Do not use f64 to lower memcpy if source is string constant. It's
1836       // better to use i32 to avoid the loads.
1837       return MVT::f64;
1838     }
1839   }
1840   if (Subtarget->is64Bit() && Size >= 8)
1841     return MVT::i64;
1842   return MVT::i32;
1843 }
1844
1845 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1846   if (VT == MVT::f32)
1847     return X86ScalarSSEf32;
1848   else if (VT == MVT::f64)
1849     return X86ScalarSSEf64;
1850   return true;
1851 }
1852
1853 bool
1854 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1855                                                   unsigned,
1856                                                   unsigned,
1857                                                   bool *Fast) const {
1858   if (Fast)
1859     *Fast = Subtarget->isUnalignedMemAccessFast();
1860   return true;
1861 }
1862
1863 /// Return the entry encoding for a jump table in the
1864 /// current function.  The returned value is a member of the
1865 /// MachineJumpTableInfo::JTEntryKind enum.
1866 unsigned X86TargetLowering::getJumpTableEncoding() const {
1867   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1868   // symbol.
1869   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1870       Subtarget->isPICStyleGOT())
1871     return MachineJumpTableInfo::EK_Custom32;
1872
1873   // Otherwise, use the normal jump table encoding heuristics.
1874   return TargetLowering::getJumpTableEncoding();
1875 }
1876
1877 const MCExpr *
1878 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1879                                              const MachineBasicBlock *MBB,
1880                                              unsigned uid,MCContext &Ctx) const{
1881   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1882          Subtarget->isPICStyleGOT());
1883   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1884   // entries.
1885   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1886                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1887 }
1888
1889 /// Returns relocation base for the given PIC jumptable.
1890 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1891                                                     SelectionDAG &DAG) const {
1892   if (!Subtarget->is64Bit())
1893     // This doesn't have SDLoc associated with it, but is not really the
1894     // same as a Register.
1895     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1896   return Table;
1897 }
1898
1899 /// This returns the relocation base for the given PIC jumptable,
1900 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1901 const MCExpr *X86TargetLowering::
1902 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1903                              MCContext &Ctx) const {
1904   // X86-64 uses RIP relative addressing based on the jump table label.
1905   if (Subtarget->isPICStyleRIPRel())
1906     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1907
1908   // Otherwise, the reference is relative to the PIC base.
1909   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1910 }
1911
1912 // FIXME: Why this routine is here? Move to RegInfo!
1913 std::pair<const TargetRegisterClass*, uint8_t>
1914 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1915   const TargetRegisterClass *RRC = nullptr;
1916   uint8_t Cost = 1;
1917   switch (VT.SimpleTy) {
1918   default:
1919     return TargetLowering::findRepresentativeClass(VT);
1920   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1921     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1922     break;
1923   case MVT::x86mmx:
1924     RRC = &X86::VR64RegClass;
1925     break;
1926   case MVT::f32: case MVT::f64:
1927   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1928   case MVT::v4f32: case MVT::v2f64:
1929   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1930   case MVT::v4f64:
1931     RRC = &X86::VR128RegClass;
1932     break;
1933   }
1934   return std::make_pair(RRC, Cost);
1935 }
1936
1937 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1938                                                unsigned &Offset) const {
1939   if (!Subtarget->isTargetLinux())
1940     return false;
1941
1942   if (Subtarget->is64Bit()) {
1943     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1944     Offset = 0x28;
1945     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1946       AddressSpace = 256;
1947     else
1948       AddressSpace = 257;
1949   } else {
1950     // %gs:0x14 on i386
1951     Offset = 0x14;
1952     AddressSpace = 256;
1953   }
1954   return true;
1955 }
1956
1957 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1958                                             unsigned DestAS) const {
1959   assert(SrcAS != DestAS && "Expected different address spaces!");
1960
1961   return SrcAS < 256 && DestAS < 256;
1962 }
1963
1964 //===----------------------------------------------------------------------===//
1965 //               Return Value Calling Convention Implementation
1966 //===----------------------------------------------------------------------===//
1967
1968 #include "X86GenCallingConv.inc"
1969
1970 bool
1971 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1972                                   MachineFunction &MF, bool isVarArg,
1973                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1974                         LLVMContext &Context) const {
1975   SmallVector<CCValAssign, 16> RVLocs;
1976   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1977   return CCInfo.CheckReturn(Outs, RetCC_X86);
1978 }
1979
1980 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1981   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1982   return ScratchRegs;
1983 }
1984
1985 SDValue
1986 X86TargetLowering::LowerReturn(SDValue Chain,
1987                                CallingConv::ID CallConv, bool isVarArg,
1988                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1989                                const SmallVectorImpl<SDValue> &OutVals,
1990                                SDLoc dl, SelectionDAG &DAG) const {
1991   MachineFunction &MF = DAG.getMachineFunction();
1992   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1993
1994   SmallVector<CCValAssign, 16> RVLocs;
1995   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1996   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1997
1998   SDValue Flag;
1999   SmallVector<SDValue, 6> RetOps;
2000   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2001   // Operand #1 = Bytes To Pop
2002   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2003                    MVT::i16));
2004
2005   // Copy the result values into the output registers.
2006   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2007     CCValAssign &VA = RVLocs[i];
2008     assert(VA.isRegLoc() && "Can only return in registers!");
2009     SDValue ValToCopy = OutVals[i];
2010     EVT ValVT = ValToCopy.getValueType();
2011
2012     // Promote values to the appropriate types.
2013     if (VA.getLocInfo() == CCValAssign::SExt)
2014       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2015     else if (VA.getLocInfo() == CCValAssign::ZExt)
2016       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2017     else if (VA.getLocInfo() == CCValAssign::AExt)
2018       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2019     else if (VA.getLocInfo() == CCValAssign::BCvt)
2020       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2021
2022     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2023            "Unexpected FP-extend for return value.");
2024
2025     // If this is x86-64, and we disabled SSE, we can't return FP values,
2026     // or SSE or MMX vectors.
2027     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2028          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2029           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2030       report_fatal_error("SSE register return with SSE disabled");
2031     }
2032     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2033     // llvm-gcc has never done it right and no one has noticed, so this
2034     // should be OK for now.
2035     if (ValVT == MVT::f64 &&
2036         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2037       report_fatal_error("SSE2 register return with SSE2 disabled");
2038
2039     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2040     // the RET instruction and handled by the FP Stackifier.
2041     if (VA.getLocReg() == X86::FP0 ||
2042         VA.getLocReg() == X86::FP1) {
2043       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2044       // change the value to the FP stack register class.
2045       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2046         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2047       RetOps.push_back(ValToCopy);
2048       // Don't emit a copytoreg.
2049       continue;
2050     }
2051
2052     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2053     // which is returned in RAX / RDX.
2054     if (Subtarget->is64Bit()) {
2055       if (ValVT == MVT::x86mmx) {
2056         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2057           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2058           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2059                                   ValToCopy);
2060           // If we don't have SSE2 available, convert to v4f32 so the generated
2061           // register is legal.
2062           if (!Subtarget->hasSSE2())
2063             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2064         }
2065       }
2066     }
2067
2068     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2069     Flag = Chain.getValue(1);
2070     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2071   }
2072
2073   // The x86-64 ABIs require that for returning structs by value we copy
2074   // the sret argument into %rax/%eax (depending on ABI) for the return.
2075   // Win32 requires us to put the sret argument to %eax as well.
2076   // We saved the argument into a virtual register in the entry block,
2077   // so now we copy the value out and into %rax/%eax.
2078   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2079       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2080     MachineFunction &MF = DAG.getMachineFunction();
2081     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2082     unsigned Reg = FuncInfo->getSRetReturnReg();
2083     assert(Reg &&
2084            "SRetReturnReg should have been set in LowerFormalArguments().");
2085     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2086
2087     unsigned RetValReg
2088         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2089           X86::RAX : X86::EAX;
2090     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2091     Flag = Chain.getValue(1);
2092
2093     // RAX/EAX now acts like a return value.
2094     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2095   }
2096
2097   RetOps[0] = Chain;  // Update chain.
2098
2099   // Add the flag if we have it.
2100   if (Flag.getNode())
2101     RetOps.push_back(Flag);
2102
2103   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2104 }
2105
2106 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2107   if (N->getNumValues() != 1)
2108     return false;
2109   if (!N->hasNUsesOfValue(1, 0))
2110     return false;
2111
2112   SDValue TCChain = Chain;
2113   SDNode *Copy = *N->use_begin();
2114   if (Copy->getOpcode() == ISD::CopyToReg) {
2115     // If the copy has a glue operand, we conservatively assume it isn't safe to
2116     // perform a tail call.
2117     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2118       return false;
2119     TCChain = Copy->getOperand(0);
2120   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2121     return false;
2122
2123   bool HasRet = false;
2124   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2125        UI != UE; ++UI) {
2126     if (UI->getOpcode() != X86ISD::RET_FLAG)
2127       return false;
2128     // If we are returning more than one value, we can definitely
2129     // not make a tail call see PR19530
2130     if (UI->getNumOperands() > 4)
2131       return false;
2132     if (UI->getNumOperands() == 4 &&
2133         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2134       return false;
2135     HasRet = true;
2136   }
2137
2138   if (!HasRet)
2139     return false;
2140
2141   Chain = TCChain;
2142   return true;
2143 }
2144
2145 EVT
2146 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2147                                             ISD::NodeType ExtendKind) const {
2148   MVT ReturnMVT;
2149   // TODO: Is this also valid on 32-bit?
2150   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2151     ReturnMVT = MVT::i8;
2152   else
2153     ReturnMVT = MVT::i32;
2154
2155   EVT MinVT = getRegisterType(Context, ReturnMVT);
2156   return VT.bitsLT(MinVT) ? MinVT : VT;
2157 }
2158
2159 /// Lower the result values of a call into the
2160 /// appropriate copies out of appropriate physical registers.
2161 ///
2162 SDValue
2163 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2164                                    CallingConv::ID CallConv, bool isVarArg,
2165                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2166                                    SDLoc dl, SelectionDAG &DAG,
2167                                    SmallVectorImpl<SDValue> &InVals) const {
2168
2169   // Assign locations to each value returned by this call.
2170   SmallVector<CCValAssign, 16> RVLocs;
2171   bool Is64Bit = Subtarget->is64Bit();
2172   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2173                  *DAG.getContext());
2174   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2175
2176   // Copy all of the result registers out of their specified physreg.
2177   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2178     CCValAssign &VA = RVLocs[i];
2179     EVT CopyVT = VA.getValVT();
2180
2181     // If this is x86-64, and we disabled SSE, we can't return FP values
2182     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2183         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2184       report_fatal_error("SSE register return with SSE disabled");
2185     }
2186
2187     // If we prefer to use the value in xmm registers, copy it out as f80 and
2188     // use a truncate to move it from fp stack reg to xmm reg.
2189     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2190         isScalarFPTypeInSSEReg(VA.getValVT()))
2191       CopyVT = MVT::f80;
2192
2193     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2194                                CopyVT, InFlag).getValue(1);
2195     SDValue Val = Chain.getValue(0);
2196
2197     if (CopyVT != VA.getValVT())
2198       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2199                         // This truncation won't change the value.
2200                         DAG.getIntPtrConstant(1));
2201
2202     InFlag = Chain.getValue(2);
2203     InVals.push_back(Val);
2204   }
2205
2206   return Chain;
2207 }
2208
2209 //===----------------------------------------------------------------------===//
2210 //                C & StdCall & Fast Calling Convention implementation
2211 //===----------------------------------------------------------------------===//
2212 //  StdCall calling convention seems to be standard for many Windows' API
2213 //  routines and around. It differs from C calling convention just a little:
2214 //  callee should clean up the stack, not caller. Symbols should be also
2215 //  decorated in some fancy way :) It doesn't support any vector arguments.
2216 //  For info on fast calling convention see Fast Calling Convention (tail call)
2217 //  implementation LowerX86_32FastCCCallTo.
2218
2219 /// CallIsStructReturn - Determines whether a call uses struct return
2220 /// semantics.
2221 enum StructReturnType {
2222   NotStructReturn,
2223   RegStructReturn,
2224   StackStructReturn
2225 };
2226 static StructReturnType
2227 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2228   if (Outs.empty())
2229     return NotStructReturn;
2230
2231   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2232   if (!Flags.isSRet())
2233     return NotStructReturn;
2234   if (Flags.isInReg())
2235     return RegStructReturn;
2236   return StackStructReturn;
2237 }
2238
2239 /// Determines whether a function uses struct return semantics.
2240 static StructReturnType
2241 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2242   if (Ins.empty())
2243     return NotStructReturn;
2244
2245   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2246   if (!Flags.isSRet())
2247     return NotStructReturn;
2248   if (Flags.isInReg())
2249     return RegStructReturn;
2250   return StackStructReturn;
2251 }
2252
2253 /// Make a copy of an aggregate at address specified by "Src" to address
2254 /// "Dst" with size and alignment information specified by the specific
2255 /// parameter attribute. The copy will be passed as a byval function parameter.
2256 static SDValue
2257 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2258                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2259                           SDLoc dl) {
2260   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2261
2262   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2263                        /*isVolatile*/false, /*AlwaysInline=*/true,
2264                        MachinePointerInfo(), MachinePointerInfo());
2265 }
2266
2267 /// Return true if the calling convention is one that
2268 /// supports tail call optimization.
2269 static bool IsTailCallConvention(CallingConv::ID CC) {
2270   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2271           CC == CallingConv::HiPE);
2272 }
2273
2274 /// \brief Return true if the calling convention is a C calling convention.
2275 static bool IsCCallConvention(CallingConv::ID CC) {
2276   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2277           CC == CallingConv::X86_64_SysV);
2278 }
2279
2280 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2281   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2282     return false;
2283
2284   CallSite CS(CI);
2285   CallingConv::ID CalleeCC = CS.getCallingConv();
2286   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2287     return false;
2288
2289   return true;
2290 }
2291
2292 /// Return true if the function is being made into
2293 /// a tailcall target by changing its ABI.
2294 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2295                                    bool GuaranteedTailCallOpt) {
2296   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2297 }
2298
2299 SDValue
2300 X86TargetLowering::LowerMemArgument(SDValue Chain,
2301                                     CallingConv::ID CallConv,
2302                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2303                                     SDLoc dl, SelectionDAG &DAG,
2304                                     const CCValAssign &VA,
2305                                     MachineFrameInfo *MFI,
2306                                     unsigned i) const {
2307   // Create the nodes corresponding to a load from this parameter slot.
2308   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2309   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2310       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2311   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2312   EVT ValVT;
2313
2314   // If value is passed by pointer we have address passed instead of the value
2315   // itself.
2316   if (VA.getLocInfo() == CCValAssign::Indirect)
2317     ValVT = VA.getLocVT();
2318   else
2319     ValVT = VA.getValVT();
2320
2321   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2322   // changed with more analysis.
2323   // In case of tail call optimization mark all arguments mutable. Since they
2324   // could be overwritten by lowering of arguments in case of a tail call.
2325   if (Flags.isByVal()) {
2326     unsigned Bytes = Flags.getByValSize();
2327     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2328     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2329     return DAG.getFrameIndex(FI, getPointerTy());
2330   } else {
2331     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2332                                     VA.getLocMemOffset(), isImmutable);
2333     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2334     return DAG.getLoad(ValVT, dl, Chain, FIN,
2335                        MachinePointerInfo::getFixedStack(FI),
2336                        false, false, false, 0);
2337   }
2338 }
2339
2340 // FIXME: Get this from tablegen.
2341 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2342                                                 const X86Subtarget *Subtarget) {
2343   assert(Subtarget->is64Bit());
2344
2345   if (Subtarget->isCallingConvWin64(CallConv)) {
2346     static const MCPhysReg GPR64ArgRegsWin64[] = {
2347       X86::RCX, X86::RDX, X86::R8,  X86::R9
2348     };
2349     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2350   }
2351
2352   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2353     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2354   };
2355   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2356 }
2357
2358 // FIXME: Get this from tablegen.
2359 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2360                                                 CallingConv::ID CallConv,
2361                                                 const X86Subtarget *Subtarget) {
2362   assert(Subtarget->is64Bit());
2363   if (Subtarget->isCallingConvWin64(CallConv)) {
2364     // The XMM registers which might contain var arg parameters are shadowed
2365     // in their paired GPR.  So we only need to save the GPR to their home
2366     // slots.
2367     // TODO: __vectorcall will change this.
2368     return None;
2369   }
2370
2371   const Function *Fn = MF.getFunction();
2372   bool NoImplicitFloatOps = Fn->getAttributes().
2373       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2374   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2375          "SSE register cannot be used when SSE is disabled!");
2376   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2377       !Subtarget->hasSSE1())
2378     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2379     // registers.
2380     return None;
2381
2382   static const MCPhysReg XMMArgRegs64Bit[] = {
2383     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2384     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2385   };
2386   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2387 }
2388
2389 SDValue
2390 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2391                                         CallingConv::ID CallConv,
2392                                         bool isVarArg,
2393                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2394                                         SDLoc dl,
2395                                         SelectionDAG &DAG,
2396                                         SmallVectorImpl<SDValue> &InVals)
2397                                           const {
2398   MachineFunction &MF = DAG.getMachineFunction();
2399   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2400
2401   const Function* Fn = MF.getFunction();
2402   if (Fn->hasExternalLinkage() &&
2403       Subtarget->isTargetCygMing() &&
2404       Fn->getName() == "main")
2405     FuncInfo->setForceFramePointer(true);
2406
2407   MachineFrameInfo *MFI = MF.getFrameInfo();
2408   bool Is64Bit = Subtarget->is64Bit();
2409   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2410
2411   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2412          "Var args not supported with calling convention fastcc, ghc or hipe");
2413
2414   // Assign locations to all of the incoming arguments.
2415   SmallVector<CCValAssign, 16> ArgLocs;
2416   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2417
2418   // Allocate shadow area for Win64
2419   if (IsWin64)
2420     CCInfo.AllocateStack(32, 8);
2421
2422   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2423
2424   unsigned LastVal = ~0U;
2425   SDValue ArgValue;
2426   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2427     CCValAssign &VA = ArgLocs[i];
2428     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2429     // places.
2430     assert(VA.getValNo() != LastVal &&
2431            "Don't support value assigned to multiple locs yet");
2432     (void)LastVal;
2433     LastVal = VA.getValNo();
2434
2435     if (VA.isRegLoc()) {
2436       EVT RegVT = VA.getLocVT();
2437       const TargetRegisterClass *RC;
2438       if (RegVT == MVT::i32)
2439         RC = &X86::GR32RegClass;
2440       else if (Is64Bit && RegVT == MVT::i64)
2441         RC = &X86::GR64RegClass;
2442       else if (RegVT == MVT::f32)
2443         RC = &X86::FR32RegClass;
2444       else if (RegVT == MVT::f64)
2445         RC = &X86::FR64RegClass;
2446       else if (RegVT.is512BitVector())
2447         RC = &X86::VR512RegClass;
2448       else if (RegVT.is256BitVector())
2449         RC = &X86::VR256RegClass;
2450       else if (RegVT.is128BitVector())
2451         RC = &X86::VR128RegClass;
2452       else if (RegVT == MVT::x86mmx)
2453         RC = &X86::VR64RegClass;
2454       else if (RegVT == MVT::i1)
2455         RC = &X86::VK1RegClass;
2456       else if (RegVT == MVT::v8i1)
2457         RC = &X86::VK8RegClass;
2458       else if (RegVT == MVT::v16i1)
2459         RC = &X86::VK16RegClass;
2460       else if (RegVT == MVT::v32i1)
2461         RC = &X86::VK32RegClass;
2462       else if (RegVT == MVT::v64i1)
2463         RC = &X86::VK64RegClass;
2464       else
2465         llvm_unreachable("Unknown argument type!");
2466
2467       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2468       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2469
2470       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2471       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2472       // right size.
2473       if (VA.getLocInfo() == CCValAssign::SExt)
2474         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2475                                DAG.getValueType(VA.getValVT()));
2476       else if (VA.getLocInfo() == CCValAssign::ZExt)
2477         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2478                                DAG.getValueType(VA.getValVT()));
2479       else if (VA.getLocInfo() == CCValAssign::BCvt)
2480         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2481
2482       if (VA.isExtInLoc()) {
2483         // Handle MMX values passed in XMM regs.
2484         if (RegVT.isVector())
2485           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2486         else
2487           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2488       }
2489     } else {
2490       assert(VA.isMemLoc());
2491       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2492     }
2493
2494     // If value is passed via pointer - do a load.
2495     if (VA.getLocInfo() == CCValAssign::Indirect)
2496       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2497                              MachinePointerInfo(), false, false, false, 0);
2498
2499     InVals.push_back(ArgValue);
2500   }
2501
2502   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2503     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2504       // The x86-64 ABIs require that for returning structs by value we copy
2505       // the sret argument into %rax/%eax (depending on ABI) for the return.
2506       // Win32 requires us to put the sret argument to %eax as well.
2507       // Save the argument into a virtual register so that we can access it
2508       // from the return points.
2509       if (Ins[i].Flags.isSRet()) {
2510         unsigned Reg = FuncInfo->getSRetReturnReg();
2511         if (!Reg) {
2512           MVT PtrTy = getPointerTy();
2513           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2514           FuncInfo->setSRetReturnReg(Reg);
2515         }
2516         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2517         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2518         break;
2519       }
2520     }
2521   }
2522
2523   unsigned StackSize = CCInfo.getNextStackOffset();
2524   // Align stack specially for tail calls.
2525   if (FuncIsMadeTailCallSafe(CallConv,
2526                              MF.getTarget().Options.GuaranteedTailCallOpt))
2527     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2528
2529   // If the function takes variable number of arguments, make a frame index for
2530   // the start of the first vararg value... for expansion of llvm.va_start. We
2531   // can skip this if there are no va_start calls.
2532   if (MFI->hasVAStart() &&
2533       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2534                    CallConv != CallingConv::X86_ThisCall))) {
2535     FuncInfo->setVarArgsFrameIndex(
2536         MFI->CreateFixedObject(1, StackSize, true));
2537   }
2538
2539   // Figure out if XMM registers are in use.
2540   assert(!(MF.getTarget().Options.UseSoftFloat &&
2541            Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
2542                                             Attribute::NoImplicitFloat)) &&
2543          "SSE register cannot be used when SSE is disabled!");
2544
2545   // 64-bit calling conventions support varargs and register parameters, so we
2546   // have to do extra work to spill them in the prologue.
2547   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2548     // Find the first unallocated argument registers.
2549     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2550     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2551     unsigned NumIntRegs =
2552         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2553     unsigned NumXMMRegs =
2554         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2555     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2556            "SSE register cannot be used when SSE is disabled!");
2557
2558     // Gather all the live in physical registers.
2559     SmallVector<SDValue, 6> LiveGPRs;
2560     SmallVector<SDValue, 8> LiveXMMRegs;
2561     SDValue ALVal;
2562     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2563       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2564       LiveGPRs.push_back(
2565           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2566     }
2567     if (!ArgXMMs.empty()) {
2568       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2569       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2570       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2571         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2572         LiveXMMRegs.push_back(
2573             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2574       }
2575     }
2576
2577     if (IsWin64) {
2578       const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2579       // Get to the caller-allocated home save location.  Add 8 to account
2580       // for the return address.
2581       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2582       FuncInfo->setRegSaveFrameIndex(
2583           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2584       // Fixup to set vararg frame on shadow area (4 x i64).
2585       if (NumIntRegs < 4)
2586         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2587     } else {
2588       // For X86-64, if there are vararg parameters that are passed via
2589       // registers, then we must store them to their spots on the stack so
2590       // they may be loaded by deferencing the result of va_next.
2591       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2592       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2593       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2594           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2595     }
2596
2597     // Store the integer parameter registers.
2598     SmallVector<SDValue, 8> MemOps;
2599     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2600                                       getPointerTy());
2601     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2602     for (SDValue Val : LiveGPRs) {
2603       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2604                                 DAG.getIntPtrConstant(Offset));
2605       SDValue Store =
2606         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2607                      MachinePointerInfo::getFixedStack(
2608                        FuncInfo->getRegSaveFrameIndex(), Offset),
2609                      false, false, 0);
2610       MemOps.push_back(Store);
2611       Offset += 8;
2612     }
2613
2614     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2615       // Now store the XMM (fp + vector) parameter registers.
2616       SmallVector<SDValue, 12> SaveXMMOps;
2617       SaveXMMOps.push_back(Chain);
2618       SaveXMMOps.push_back(ALVal);
2619       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2620                              FuncInfo->getRegSaveFrameIndex()));
2621       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2622                              FuncInfo->getVarArgsFPOffset()));
2623       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2624                         LiveXMMRegs.end());
2625       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2626                                    MVT::Other, SaveXMMOps));
2627     }
2628
2629     if (!MemOps.empty())
2630       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2631   }
2632
2633   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2634     // Find the largest legal vector type.
2635     MVT VecVT = MVT::Other;
2636     // FIXME: Only some x86_32 calling conventions support AVX512.
2637     if (Subtarget->hasAVX512() &&
2638         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2639                      CallConv == CallingConv::Intel_OCL_BI)))
2640       VecVT = MVT::v16f32;
2641     else if (Subtarget->hasAVX())
2642       VecVT = MVT::v8f32;
2643     else if (Subtarget->hasSSE2())
2644       VecVT = MVT::v4f32;
2645
2646     // We forward some GPRs and some vector types.
2647     SmallVector<MVT, 2> RegParmTypes;
2648     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2649     RegParmTypes.push_back(IntVT);
2650     if (VecVT != MVT::Other)
2651       RegParmTypes.push_back(VecVT);
2652
2653     // Compute the set of forwarded registers. The rest are scratch.
2654     SmallVectorImpl<ForwardedRegister> &Forwards =
2655         FuncInfo->getForwardedMustTailRegParms();
2656     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2657
2658     // Conservatively forward AL on x86_64, since it might be used for varargs.
2659     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2660       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2661       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2662     }
2663
2664     // Copy all forwards from physical to virtual registers.
2665     for (ForwardedRegister &F : Forwards) {
2666       // FIXME: Can we use a less constrained schedule?
2667       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2668       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2669       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2670     }
2671   }
2672
2673   // Some CCs need callee pop.
2674   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2675                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2676     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2677   } else {
2678     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2679     // If this is an sret function, the return should pop the hidden pointer.
2680     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2681         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2682         argsAreStructReturn(Ins) == StackStructReturn)
2683       FuncInfo->setBytesToPopOnReturn(4);
2684   }
2685
2686   if (!Is64Bit) {
2687     // RegSaveFrameIndex is X86-64 only.
2688     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2689     if (CallConv == CallingConv::X86_FastCall ||
2690         CallConv == CallingConv::X86_ThisCall)
2691       // fastcc functions can't have varargs.
2692       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2693   }
2694
2695   FuncInfo->setArgumentStackSize(StackSize);
2696
2697   return Chain;
2698 }
2699
2700 SDValue
2701 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2702                                     SDValue StackPtr, SDValue Arg,
2703                                     SDLoc dl, SelectionDAG &DAG,
2704                                     const CCValAssign &VA,
2705                                     ISD::ArgFlagsTy Flags) const {
2706   unsigned LocMemOffset = VA.getLocMemOffset();
2707   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2708   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2709   if (Flags.isByVal())
2710     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2711
2712   return DAG.getStore(Chain, dl, Arg, PtrOff,
2713                       MachinePointerInfo::getStack(LocMemOffset),
2714                       false, false, 0);
2715 }
2716
2717 /// Emit a load of return address if tail call
2718 /// optimization is performed and it is required.
2719 SDValue
2720 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2721                                            SDValue &OutRetAddr, SDValue Chain,
2722                                            bool IsTailCall, bool Is64Bit,
2723                                            int FPDiff, SDLoc dl) const {
2724   // Adjust the Return address stack slot.
2725   EVT VT = getPointerTy();
2726   OutRetAddr = getReturnAddressFrameIndex(DAG);
2727
2728   // Load the "old" Return address.
2729   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2730                            false, false, false, 0);
2731   return SDValue(OutRetAddr.getNode(), 1);
2732 }
2733
2734 /// Emit a store of the return address if tail call
2735 /// optimization is performed and it is required (FPDiff!=0).
2736 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2737                                         SDValue Chain, SDValue RetAddrFrIdx,
2738                                         EVT PtrVT, unsigned SlotSize,
2739                                         int FPDiff, SDLoc dl) {
2740   // Store the return address to the appropriate stack slot.
2741   if (!FPDiff) return Chain;
2742   // Calculate the new stack slot for the return address.
2743   int NewReturnAddrFI =
2744     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2745                                          false);
2746   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2747   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2748                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2749                        false, false, 0);
2750   return Chain;
2751 }
2752
2753 SDValue
2754 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2755                              SmallVectorImpl<SDValue> &InVals) const {
2756   SelectionDAG &DAG                     = CLI.DAG;
2757   SDLoc &dl                             = CLI.DL;
2758   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2759   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2760   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2761   SDValue Chain                         = CLI.Chain;
2762   SDValue Callee                        = CLI.Callee;
2763   CallingConv::ID CallConv              = CLI.CallConv;
2764   bool &isTailCall                      = CLI.IsTailCall;
2765   bool isVarArg                         = CLI.IsVarArg;
2766
2767   MachineFunction &MF = DAG.getMachineFunction();
2768   bool Is64Bit        = Subtarget->is64Bit();
2769   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2770   StructReturnType SR = callIsStructReturn(Outs);
2771   bool IsSibcall      = false;
2772   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2773
2774   if (MF.getTarget().Options.DisableTailCalls)
2775     isTailCall = false;
2776
2777   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2778   if (IsMustTail) {
2779     // Force this to be a tail call.  The verifier rules are enough to ensure
2780     // that we can lower this successfully without moving the return address
2781     // around.
2782     isTailCall = true;
2783   } else if (isTailCall) {
2784     // Check if it's really possible to do a tail call.
2785     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2786                     isVarArg, SR != NotStructReturn,
2787                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2788                     Outs, OutVals, Ins, DAG);
2789
2790     // Sibcalls are automatically detected tailcalls which do not require
2791     // ABI changes.
2792     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2793       IsSibcall = true;
2794
2795     if (isTailCall)
2796       ++NumTailCalls;
2797   }
2798
2799   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2800          "Var args not supported with calling convention fastcc, ghc or hipe");
2801
2802   // Analyze operands of the call, assigning locations to each operand.
2803   SmallVector<CCValAssign, 16> ArgLocs;
2804   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2805
2806   // Allocate shadow area for Win64
2807   if (IsWin64)
2808     CCInfo.AllocateStack(32, 8);
2809
2810   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2811
2812   // Get a count of how many bytes are to be pushed on the stack.
2813   unsigned NumBytes = CCInfo.getNextStackOffset();
2814   if (IsSibcall)
2815     // This is a sibcall. The memory operands are available in caller's
2816     // own caller's stack.
2817     NumBytes = 0;
2818   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2819            IsTailCallConvention(CallConv))
2820     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2821
2822   int FPDiff = 0;
2823   if (isTailCall && !IsSibcall && !IsMustTail) {
2824     // Lower arguments at fp - stackoffset + fpdiff.
2825     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2826
2827     FPDiff = NumBytesCallerPushed - NumBytes;
2828
2829     // Set the delta of movement of the returnaddr stackslot.
2830     // But only set if delta is greater than previous delta.
2831     if (FPDiff < X86Info->getTCReturnAddrDelta())
2832       X86Info->setTCReturnAddrDelta(FPDiff);
2833   }
2834
2835   unsigned NumBytesToPush = NumBytes;
2836   unsigned NumBytesToPop = NumBytes;
2837
2838   // If we have an inalloca argument, all stack space has already been allocated
2839   // for us and be right at the top of the stack.  We don't support multiple
2840   // arguments passed in memory when using inalloca.
2841   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2842     NumBytesToPush = 0;
2843     if (!ArgLocs.back().isMemLoc())
2844       report_fatal_error("cannot use inalloca attribute on a register "
2845                          "parameter");
2846     if (ArgLocs.back().getLocMemOffset() != 0)
2847       report_fatal_error("any parameter with the inalloca attribute must be "
2848                          "the only memory argument");
2849   }
2850
2851   if (!IsSibcall)
2852     Chain = DAG.getCALLSEQ_START(
2853         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2854
2855   SDValue RetAddrFrIdx;
2856   // Load return address for tail calls.
2857   if (isTailCall && FPDiff)
2858     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2859                                     Is64Bit, FPDiff, dl);
2860
2861   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2862   SmallVector<SDValue, 8> MemOpChains;
2863   SDValue StackPtr;
2864
2865   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2866   // of tail call optimization arguments are handle later.
2867   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2868       DAG.getSubtarget().getRegisterInfo());
2869   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2870     // Skip inalloca arguments, they have already been written.
2871     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2872     if (Flags.isInAlloca())
2873       continue;
2874
2875     CCValAssign &VA = ArgLocs[i];
2876     EVT RegVT = VA.getLocVT();
2877     SDValue Arg = OutVals[i];
2878     bool isByVal = Flags.isByVal();
2879
2880     // Promote the value if needed.
2881     switch (VA.getLocInfo()) {
2882     default: llvm_unreachable("Unknown loc info!");
2883     case CCValAssign::Full: break;
2884     case CCValAssign::SExt:
2885       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2886       break;
2887     case CCValAssign::ZExt:
2888       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2889       break;
2890     case CCValAssign::AExt:
2891       if (RegVT.is128BitVector()) {
2892         // Special case: passing MMX values in XMM registers.
2893         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2894         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2895         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2896       } else
2897         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2898       break;
2899     case CCValAssign::BCvt:
2900       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2901       break;
2902     case CCValAssign::Indirect: {
2903       // Store the argument.
2904       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2905       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2906       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2907                            MachinePointerInfo::getFixedStack(FI),
2908                            false, false, 0);
2909       Arg = SpillSlot;
2910       break;
2911     }
2912     }
2913
2914     if (VA.isRegLoc()) {
2915       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2916       if (isVarArg && IsWin64) {
2917         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2918         // shadow reg if callee is a varargs function.
2919         unsigned ShadowReg = 0;
2920         switch (VA.getLocReg()) {
2921         case X86::XMM0: ShadowReg = X86::RCX; break;
2922         case X86::XMM1: ShadowReg = X86::RDX; break;
2923         case X86::XMM2: ShadowReg = X86::R8; break;
2924         case X86::XMM3: ShadowReg = X86::R9; break;
2925         }
2926         if (ShadowReg)
2927           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2928       }
2929     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2930       assert(VA.isMemLoc());
2931       if (!StackPtr.getNode())
2932         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2933                                       getPointerTy());
2934       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2935                                              dl, DAG, VA, Flags));
2936     }
2937   }
2938
2939   if (!MemOpChains.empty())
2940     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2941
2942   if (Subtarget->isPICStyleGOT()) {
2943     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2944     // GOT pointer.
2945     if (!isTailCall) {
2946       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2947                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2948     } else {
2949       // If we are tail calling and generating PIC/GOT style code load the
2950       // address of the callee into ECX. The value in ecx is used as target of
2951       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2952       // for tail calls on PIC/GOT architectures. Normally we would just put the
2953       // address of GOT into ebx and then call target@PLT. But for tail calls
2954       // ebx would be restored (since ebx is callee saved) before jumping to the
2955       // target@PLT.
2956
2957       // Note: The actual moving to ECX is done further down.
2958       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2959       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2960           !G->getGlobal()->hasProtectedVisibility())
2961         Callee = LowerGlobalAddress(Callee, DAG);
2962       else if (isa<ExternalSymbolSDNode>(Callee))
2963         Callee = LowerExternalSymbol(Callee, DAG);
2964     }
2965   }
2966
2967   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2968     // From AMD64 ABI document:
2969     // For calls that may call functions that use varargs or stdargs
2970     // (prototype-less calls or calls to functions containing ellipsis (...) in
2971     // the declaration) %al is used as hidden argument to specify the number
2972     // of SSE registers used. The contents of %al do not need to match exactly
2973     // the number of registers, but must be an ubound on the number of SSE
2974     // registers used and is in the range 0 - 8 inclusive.
2975
2976     // Count the number of XMM registers allocated.
2977     static const MCPhysReg XMMArgRegs[] = {
2978       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2979       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2980     };
2981     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2982     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2983            && "SSE registers cannot be used when SSE is disabled");
2984
2985     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2986                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2987   }
2988
2989   if (isVarArg && IsMustTail) {
2990     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2991     for (const auto &F : Forwards) {
2992       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2993       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2994     }
2995   }
2996
2997   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2998   // don't need this because the eligibility check rejects calls that require
2999   // shuffling arguments passed in memory.
3000   if (!IsSibcall && isTailCall) {
3001     // Force all the incoming stack arguments to be loaded from the stack
3002     // before any new outgoing arguments are stored to the stack, because the
3003     // outgoing stack slots may alias the incoming argument stack slots, and
3004     // the alias isn't otherwise explicit. This is slightly more conservative
3005     // than necessary, because it means that each store effectively depends
3006     // on every argument instead of just those arguments it would clobber.
3007     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3008
3009     SmallVector<SDValue, 8> MemOpChains2;
3010     SDValue FIN;
3011     int FI = 0;
3012     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3013       CCValAssign &VA = ArgLocs[i];
3014       if (VA.isRegLoc())
3015         continue;
3016       assert(VA.isMemLoc());
3017       SDValue Arg = OutVals[i];
3018       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3019       // Skip inalloca arguments.  They don't require any work.
3020       if (Flags.isInAlloca())
3021         continue;
3022       // Create frame index.
3023       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3024       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3025       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3026       FIN = DAG.getFrameIndex(FI, getPointerTy());
3027
3028       if (Flags.isByVal()) {
3029         // Copy relative to framepointer.
3030         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3031         if (!StackPtr.getNode())
3032           StackPtr = DAG.getCopyFromReg(Chain, dl,
3033                                         RegInfo->getStackRegister(),
3034                                         getPointerTy());
3035         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3036
3037         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3038                                                          ArgChain,
3039                                                          Flags, DAG, dl));
3040       } else {
3041         // Store relative to framepointer.
3042         MemOpChains2.push_back(
3043           DAG.getStore(ArgChain, dl, Arg, FIN,
3044                        MachinePointerInfo::getFixedStack(FI),
3045                        false, false, 0));
3046       }
3047     }
3048
3049     if (!MemOpChains2.empty())
3050       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3051
3052     // Store the return address to the appropriate stack slot.
3053     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3054                                      getPointerTy(), RegInfo->getSlotSize(),
3055                                      FPDiff, dl);
3056   }
3057
3058   // Build a sequence of copy-to-reg nodes chained together with token chain
3059   // and flag operands which copy the outgoing args into registers.
3060   SDValue InFlag;
3061   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3062     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3063                              RegsToPass[i].second, InFlag);
3064     InFlag = Chain.getValue(1);
3065   }
3066
3067   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3068     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3069     // In the 64-bit large code model, we have to make all calls
3070     // through a register, since the call instruction's 32-bit
3071     // pc-relative offset may not be large enough to hold the whole
3072     // address.
3073   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3074     // If the callee is a GlobalAddress node (quite common, every direct call
3075     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3076     // it.
3077
3078     // We should use extra load for direct calls to dllimported functions in
3079     // non-JIT mode.
3080     const GlobalValue *GV = G->getGlobal();
3081     if (!GV->hasDLLImportStorageClass()) {
3082       unsigned char OpFlags = 0;
3083       bool ExtraLoad = false;
3084       unsigned WrapperKind = ISD::DELETED_NODE;
3085
3086       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3087       // external symbols most go through the PLT in PIC mode.  If the symbol
3088       // has hidden or protected visibility, or if it is static or local, then
3089       // we don't need to use the PLT - we can directly call it.
3090       if (Subtarget->isTargetELF() &&
3091           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3092           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3093         OpFlags = X86II::MO_PLT;
3094       } else if (Subtarget->isPICStyleStubAny() &&
3095                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3096                  (!Subtarget->getTargetTriple().isMacOSX() ||
3097                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3098         // PC-relative references to external symbols should go through $stub,
3099         // unless we're building with the leopard linker or later, which
3100         // automatically synthesizes these stubs.
3101         OpFlags = X86II::MO_DARWIN_STUB;
3102       } else if (Subtarget->isPICStyleRIPRel() &&
3103                  isa<Function>(GV) &&
3104                  cast<Function>(GV)->getAttributes().
3105                    hasAttribute(AttributeSet::FunctionIndex,
3106                                 Attribute::NonLazyBind)) {
3107         // If the function is marked as non-lazy, generate an indirect call
3108         // which loads from the GOT directly. This avoids runtime overhead
3109         // at the cost of eager binding (and one extra byte of encoding).
3110         OpFlags = X86II::MO_GOTPCREL;
3111         WrapperKind = X86ISD::WrapperRIP;
3112         ExtraLoad = true;
3113       }
3114
3115       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3116                                           G->getOffset(), OpFlags);
3117
3118       // Add a wrapper if needed.
3119       if (WrapperKind != ISD::DELETED_NODE)
3120         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3121       // Add extra indirection if needed.
3122       if (ExtraLoad)
3123         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3124                              MachinePointerInfo::getGOT(),
3125                              false, false, false, 0);
3126     }
3127   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3128     unsigned char OpFlags = 0;
3129
3130     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3131     // external symbols should go through the PLT.
3132     if (Subtarget->isTargetELF() &&
3133         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3134       OpFlags = X86II::MO_PLT;
3135     } else if (Subtarget->isPICStyleStubAny() &&
3136                (!Subtarget->getTargetTriple().isMacOSX() ||
3137                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3138       // PC-relative references to external symbols should go through $stub,
3139       // unless we're building with the leopard linker or later, which
3140       // automatically synthesizes these stubs.
3141       OpFlags = X86II::MO_DARWIN_STUB;
3142     }
3143
3144     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3145                                          OpFlags);
3146   } else if (Subtarget->isTarget64BitILP32() && Callee->getValueType(0) == MVT::i32) {
3147     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3148     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3149   }
3150
3151   // Returns a chain & a flag for retval copy to use.
3152   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3153   SmallVector<SDValue, 8> Ops;
3154
3155   if (!IsSibcall && isTailCall) {
3156     Chain = DAG.getCALLSEQ_END(Chain,
3157                                DAG.getIntPtrConstant(NumBytesToPop, true),
3158                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3159     InFlag = Chain.getValue(1);
3160   }
3161
3162   Ops.push_back(Chain);
3163   Ops.push_back(Callee);
3164
3165   if (isTailCall)
3166     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3167
3168   // Add argument registers to the end of the list so that they are known live
3169   // into the call.
3170   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3171     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3172                                   RegsToPass[i].second.getValueType()));
3173
3174   // Add a register mask operand representing the call-preserved registers.
3175   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3176   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3177   assert(Mask && "Missing call preserved mask for calling convention");
3178   Ops.push_back(DAG.getRegisterMask(Mask));
3179
3180   if (InFlag.getNode())
3181     Ops.push_back(InFlag);
3182
3183   if (isTailCall) {
3184     // We used to do:
3185     //// If this is the first return lowered for this function, add the regs
3186     //// to the liveout set for the function.
3187     // This isn't right, although it's probably harmless on x86; liveouts
3188     // should be computed from returns not tail calls.  Consider a void
3189     // function making a tail call to a function returning int.
3190     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3191   }
3192
3193   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3194   InFlag = Chain.getValue(1);
3195
3196   // Create the CALLSEQ_END node.
3197   unsigned NumBytesForCalleeToPop;
3198   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3199                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3200     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3201   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3202            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3203            SR == StackStructReturn)
3204     // If this is a call to a struct-return function, the callee
3205     // pops the hidden struct pointer, so we have to push it back.
3206     // This is common for Darwin/X86, Linux & Mingw32 targets.
3207     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3208     NumBytesForCalleeToPop = 4;
3209   else
3210     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3211
3212   // Returns a flag for retval copy to use.
3213   if (!IsSibcall) {
3214     Chain = DAG.getCALLSEQ_END(Chain,
3215                                DAG.getIntPtrConstant(NumBytesToPop, true),
3216                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3217                                                      true),
3218                                InFlag, dl);
3219     InFlag = Chain.getValue(1);
3220   }
3221
3222   // Handle result values, copying them out of physregs into vregs that we
3223   // return.
3224   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3225                          Ins, dl, DAG, InVals);
3226 }
3227
3228 //===----------------------------------------------------------------------===//
3229 //                Fast Calling Convention (tail call) implementation
3230 //===----------------------------------------------------------------------===//
3231
3232 //  Like std call, callee cleans arguments, convention except that ECX is
3233 //  reserved for storing the tail called function address. Only 2 registers are
3234 //  free for argument passing (inreg). Tail call optimization is performed
3235 //  provided:
3236 //                * tailcallopt is enabled
3237 //                * caller/callee are fastcc
3238 //  On X86_64 architecture with GOT-style position independent code only local
3239 //  (within module) calls are supported at the moment.
3240 //  To keep the stack aligned according to platform abi the function
3241 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3242 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3243 //  If a tail called function callee has more arguments than the caller the
3244 //  caller needs to make sure that there is room to move the RETADDR to. This is
3245 //  achieved by reserving an area the size of the argument delta right after the
3246 //  original RETADDR, but before the saved framepointer or the spilled registers
3247 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3248 //  stack layout:
3249 //    arg1
3250 //    arg2
3251 //    RETADDR
3252 //    [ new RETADDR
3253 //      move area ]
3254 //    (possible EBP)
3255 //    ESI
3256 //    EDI
3257 //    local1 ..
3258
3259 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3260 /// for a 16 byte align requirement.
3261 unsigned
3262 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3263                                                SelectionDAG& DAG) const {
3264   MachineFunction &MF = DAG.getMachineFunction();
3265   const TargetMachine &TM = MF.getTarget();
3266   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3267       TM.getSubtargetImpl()->getRegisterInfo());
3268   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3269   unsigned StackAlignment = TFI.getStackAlignment();
3270   uint64_t AlignMask = StackAlignment - 1;
3271   int64_t Offset = StackSize;
3272   unsigned SlotSize = RegInfo->getSlotSize();
3273   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3274     // Number smaller than 12 so just add the difference.
3275     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3276   } else {
3277     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3278     Offset = ((~AlignMask) & Offset) + StackAlignment +
3279       (StackAlignment-SlotSize);
3280   }
3281   return Offset;
3282 }
3283
3284 /// MatchingStackOffset - Return true if the given stack call argument is
3285 /// already available in the same position (relatively) of the caller's
3286 /// incoming argument stack.
3287 static
3288 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3289                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3290                          const X86InstrInfo *TII) {
3291   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3292   int FI = INT_MAX;
3293   if (Arg.getOpcode() == ISD::CopyFromReg) {
3294     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3295     if (!TargetRegisterInfo::isVirtualRegister(VR))
3296       return false;
3297     MachineInstr *Def = MRI->getVRegDef(VR);
3298     if (!Def)
3299       return false;
3300     if (!Flags.isByVal()) {
3301       if (!TII->isLoadFromStackSlot(Def, FI))
3302         return false;
3303     } else {
3304       unsigned Opcode = Def->getOpcode();
3305       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3306           Def->getOperand(1).isFI()) {
3307         FI = Def->getOperand(1).getIndex();
3308         Bytes = Flags.getByValSize();
3309       } else
3310         return false;
3311     }
3312   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3313     if (Flags.isByVal())
3314       // ByVal argument is passed in as a pointer but it's now being
3315       // dereferenced. e.g.
3316       // define @foo(%struct.X* %A) {
3317       //   tail call @bar(%struct.X* byval %A)
3318       // }
3319       return false;
3320     SDValue Ptr = Ld->getBasePtr();
3321     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3322     if (!FINode)
3323       return false;
3324     FI = FINode->getIndex();
3325   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3326     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3327     FI = FINode->getIndex();
3328     Bytes = Flags.getByValSize();
3329   } else
3330     return false;
3331
3332   assert(FI != INT_MAX);
3333   if (!MFI->isFixedObjectIndex(FI))
3334     return false;
3335   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3336 }
3337
3338 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3339 /// for tail call optimization. Targets which want to do tail call
3340 /// optimization should implement this function.
3341 bool
3342 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3343                                                      CallingConv::ID CalleeCC,
3344                                                      bool isVarArg,
3345                                                      bool isCalleeStructRet,
3346                                                      bool isCallerStructRet,
3347                                                      Type *RetTy,
3348                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3349                                     const SmallVectorImpl<SDValue> &OutVals,
3350                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3351                                                      SelectionDAG &DAG) const {
3352   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3353     return false;
3354
3355   // If -tailcallopt is specified, make fastcc functions tail-callable.
3356   const MachineFunction &MF = DAG.getMachineFunction();
3357   const Function *CallerF = MF.getFunction();
3358
3359   // If the function return type is x86_fp80 and the callee return type is not,
3360   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3361   // perform a tailcall optimization here.
3362   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3363     return false;
3364
3365   CallingConv::ID CallerCC = CallerF->getCallingConv();
3366   bool CCMatch = CallerCC == CalleeCC;
3367   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3368   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3369
3370   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3371     if (IsTailCallConvention(CalleeCC) && CCMatch)
3372       return true;
3373     return false;
3374   }
3375
3376   // Look for obvious safe cases to perform tail call optimization that do not
3377   // require ABI changes. This is what gcc calls sibcall.
3378
3379   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3380   // emit a special epilogue.
3381   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3382       DAG.getSubtarget().getRegisterInfo());
3383   if (RegInfo->needsStackRealignment(MF))
3384     return false;
3385
3386   // Also avoid sibcall optimization if either caller or callee uses struct
3387   // return semantics.
3388   if (isCalleeStructRet || isCallerStructRet)
3389     return false;
3390
3391   // An stdcall/thiscall caller is expected to clean up its arguments; the
3392   // callee isn't going to do that.
3393   // FIXME: this is more restrictive than needed. We could produce a tailcall
3394   // when the stack adjustment matches. For example, with a thiscall that takes
3395   // only one argument.
3396   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3397                    CallerCC == CallingConv::X86_ThisCall))
3398     return false;
3399
3400   // Do not sibcall optimize vararg calls unless all arguments are passed via
3401   // registers.
3402   if (isVarArg && !Outs.empty()) {
3403
3404     // Optimizing for varargs on Win64 is unlikely to be safe without
3405     // additional testing.
3406     if (IsCalleeWin64 || IsCallerWin64)
3407       return false;
3408
3409     SmallVector<CCValAssign, 16> ArgLocs;
3410     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3411                    *DAG.getContext());
3412
3413     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3414     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3415       if (!ArgLocs[i].isRegLoc())
3416         return false;
3417   }
3418
3419   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3420   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3421   // this into a sibcall.
3422   bool Unused = false;
3423   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3424     if (!Ins[i].Used) {
3425       Unused = true;
3426       break;
3427     }
3428   }
3429   if (Unused) {
3430     SmallVector<CCValAssign, 16> RVLocs;
3431     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3432                    *DAG.getContext());
3433     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3434     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3435       CCValAssign &VA = RVLocs[i];
3436       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3437         return false;
3438     }
3439   }
3440
3441   // If the calling conventions do not match, then we'd better make sure the
3442   // results are returned in the same way as what the caller expects.
3443   if (!CCMatch) {
3444     SmallVector<CCValAssign, 16> RVLocs1;
3445     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3446                     *DAG.getContext());
3447     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3448
3449     SmallVector<CCValAssign, 16> RVLocs2;
3450     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3451                     *DAG.getContext());
3452     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3453
3454     if (RVLocs1.size() != RVLocs2.size())
3455       return false;
3456     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3457       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3458         return false;
3459       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3460         return false;
3461       if (RVLocs1[i].isRegLoc()) {
3462         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3463           return false;
3464       } else {
3465         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3466           return false;
3467       }
3468     }
3469   }
3470
3471   // If the callee takes no arguments then go on to check the results of the
3472   // call.
3473   if (!Outs.empty()) {
3474     // Check if stack adjustment is needed. For now, do not do this if any
3475     // argument is passed on the stack.
3476     SmallVector<CCValAssign, 16> ArgLocs;
3477     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3478                    *DAG.getContext());
3479
3480     // Allocate shadow area for Win64
3481     if (IsCalleeWin64)
3482       CCInfo.AllocateStack(32, 8);
3483
3484     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3485     if (CCInfo.getNextStackOffset()) {
3486       MachineFunction &MF = DAG.getMachineFunction();
3487       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3488         return false;
3489
3490       // Check if the arguments are already laid out in the right way as
3491       // the caller's fixed stack objects.
3492       MachineFrameInfo *MFI = MF.getFrameInfo();
3493       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3494       const X86InstrInfo *TII =
3495           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3496       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3497         CCValAssign &VA = ArgLocs[i];
3498         SDValue Arg = OutVals[i];
3499         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3500         if (VA.getLocInfo() == CCValAssign::Indirect)
3501           return false;
3502         if (!VA.isRegLoc()) {
3503           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3504                                    MFI, MRI, TII))
3505             return false;
3506         }
3507       }
3508     }
3509
3510     // If the tailcall address may be in a register, then make sure it's
3511     // possible to register allocate for it. In 32-bit, the call address can
3512     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3513     // callee-saved registers are restored. These happen to be the same
3514     // registers used to pass 'inreg' arguments so watch out for those.
3515     if (!Subtarget->is64Bit() &&
3516         ((!isa<GlobalAddressSDNode>(Callee) &&
3517           !isa<ExternalSymbolSDNode>(Callee)) ||
3518          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3519       unsigned NumInRegs = 0;
3520       // In PIC we need an extra register to formulate the address computation
3521       // for the callee.
3522       unsigned MaxInRegs =
3523         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3524
3525       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3526         CCValAssign &VA = ArgLocs[i];
3527         if (!VA.isRegLoc())
3528           continue;
3529         unsigned Reg = VA.getLocReg();
3530         switch (Reg) {
3531         default: break;
3532         case X86::EAX: case X86::EDX: case X86::ECX:
3533           if (++NumInRegs == MaxInRegs)
3534             return false;
3535           break;
3536         }
3537       }
3538     }
3539   }
3540
3541   return true;
3542 }
3543
3544 FastISel *
3545 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3546                                   const TargetLibraryInfo *libInfo) const {
3547   return X86::createFastISel(funcInfo, libInfo);
3548 }
3549
3550 //===----------------------------------------------------------------------===//
3551 //                           Other Lowering Hooks
3552 //===----------------------------------------------------------------------===//
3553
3554 static bool MayFoldLoad(SDValue Op) {
3555   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3556 }
3557
3558 static bool MayFoldIntoStore(SDValue Op) {
3559   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3560 }
3561
3562 static bool isTargetShuffle(unsigned Opcode) {
3563   switch(Opcode) {
3564   default: return false;
3565   case X86ISD::BLENDI:
3566   case X86ISD::PSHUFB:
3567   case X86ISD::PSHUFD:
3568   case X86ISD::PSHUFHW:
3569   case X86ISD::PSHUFLW:
3570   case X86ISD::SHUFP:
3571   case X86ISD::PALIGNR:
3572   case X86ISD::MOVLHPS:
3573   case X86ISD::MOVLHPD:
3574   case X86ISD::MOVHLPS:
3575   case X86ISD::MOVLPS:
3576   case X86ISD::MOVLPD:
3577   case X86ISD::MOVSHDUP:
3578   case X86ISD::MOVSLDUP:
3579   case X86ISD::MOVDDUP:
3580   case X86ISD::MOVSS:
3581   case X86ISD::MOVSD:
3582   case X86ISD::UNPCKL:
3583   case X86ISD::UNPCKH:
3584   case X86ISD::VPERMILPI:
3585   case X86ISD::VPERM2X128:
3586   case X86ISD::VPERMI:
3587     return true;
3588   }
3589 }
3590
3591 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3592                                     SDValue V1, SelectionDAG &DAG) {
3593   switch(Opc) {
3594   default: llvm_unreachable("Unknown x86 shuffle node");
3595   case X86ISD::MOVSHDUP:
3596   case X86ISD::MOVSLDUP:
3597   case X86ISD::MOVDDUP:
3598     return DAG.getNode(Opc, dl, VT, V1);
3599   }
3600 }
3601
3602 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3603                                     SDValue V1, unsigned TargetMask,
3604                                     SelectionDAG &DAG) {
3605   switch(Opc) {
3606   default: llvm_unreachable("Unknown x86 shuffle node");
3607   case X86ISD::PSHUFD:
3608   case X86ISD::PSHUFHW:
3609   case X86ISD::PSHUFLW:
3610   case X86ISD::VPERMILPI:
3611   case X86ISD::VPERMI:
3612     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3613   }
3614 }
3615
3616 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3617                                     SDValue V1, SDValue V2, unsigned TargetMask,
3618                                     SelectionDAG &DAG) {
3619   switch(Opc) {
3620   default: llvm_unreachable("Unknown x86 shuffle node");
3621   case X86ISD::PALIGNR:
3622   case X86ISD::VALIGN:
3623   case X86ISD::SHUFP:
3624   case X86ISD::VPERM2X128:
3625     return DAG.getNode(Opc, dl, VT, V1, V2,
3626                        DAG.getConstant(TargetMask, MVT::i8));
3627   }
3628 }
3629
3630 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3631                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3632   switch(Opc) {
3633   default: llvm_unreachable("Unknown x86 shuffle node");
3634   case X86ISD::MOVLHPS:
3635   case X86ISD::MOVLHPD:
3636   case X86ISD::MOVHLPS:
3637   case X86ISD::MOVLPS:
3638   case X86ISD::MOVLPD:
3639   case X86ISD::MOVSS:
3640   case X86ISD::MOVSD:
3641   case X86ISD::UNPCKL:
3642   case X86ISD::UNPCKH:
3643     return DAG.getNode(Opc, dl, VT, V1, V2);
3644   }
3645 }
3646
3647 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3648   MachineFunction &MF = DAG.getMachineFunction();
3649   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3650       DAG.getSubtarget().getRegisterInfo());
3651   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3652   int ReturnAddrIndex = FuncInfo->getRAIndex();
3653
3654   if (ReturnAddrIndex == 0) {
3655     // Set up a frame object for the return address.
3656     unsigned SlotSize = RegInfo->getSlotSize();
3657     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3658                                                            -(int64_t)SlotSize,
3659                                                            false);
3660     FuncInfo->setRAIndex(ReturnAddrIndex);
3661   }
3662
3663   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3664 }
3665
3666 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3667                                        bool hasSymbolicDisplacement) {
3668   // Offset should fit into 32 bit immediate field.
3669   if (!isInt<32>(Offset))
3670     return false;
3671
3672   // If we don't have a symbolic displacement - we don't have any extra
3673   // restrictions.
3674   if (!hasSymbolicDisplacement)
3675     return true;
3676
3677   // FIXME: Some tweaks might be needed for medium code model.
3678   if (M != CodeModel::Small && M != CodeModel::Kernel)
3679     return false;
3680
3681   // For small code model we assume that latest object is 16MB before end of 31
3682   // bits boundary. We may also accept pretty large negative constants knowing
3683   // that all objects are in the positive half of address space.
3684   if (M == CodeModel::Small && Offset < 16*1024*1024)
3685     return true;
3686
3687   // For kernel code model we know that all object resist in the negative half
3688   // of 32bits address space. We may not accept negative offsets, since they may
3689   // be just off and we may accept pretty large positive ones.
3690   if (M == CodeModel::Kernel && Offset >= 0)
3691     return true;
3692
3693   return false;
3694 }
3695
3696 /// isCalleePop - Determines whether the callee is required to pop its
3697 /// own arguments. Callee pop is necessary to support tail calls.
3698 bool X86::isCalleePop(CallingConv::ID CallingConv,
3699                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3700   switch (CallingConv) {
3701   default:
3702     return false;
3703   case CallingConv::X86_StdCall:
3704   case CallingConv::X86_FastCall:
3705   case CallingConv::X86_ThisCall:
3706     return !is64Bit;
3707   case CallingConv::Fast:
3708   case CallingConv::GHC:
3709   case CallingConv::HiPE:
3710     if (IsVarArg)
3711       return false;
3712     return TailCallOpt;
3713   }
3714 }
3715
3716 /// \brief Return true if the condition is an unsigned comparison operation.
3717 static bool isX86CCUnsigned(unsigned X86CC) {
3718   switch (X86CC) {
3719   default: llvm_unreachable("Invalid integer condition!");
3720   case X86::COND_E:     return true;
3721   case X86::COND_G:     return false;
3722   case X86::COND_GE:    return false;
3723   case X86::COND_L:     return false;
3724   case X86::COND_LE:    return false;
3725   case X86::COND_NE:    return true;
3726   case X86::COND_B:     return true;
3727   case X86::COND_A:     return true;
3728   case X86::COND_BE:    return true;
3729   case X86::COND_AE:    return true;
3730   }
3731   llvm_unreachable("covered switch fell through?!");
3732 }
3733
3734 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3735 /// specific condition code, returning the condition code and the LHS/RHS of the
3736 /// comparison to make.
3737 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3738                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3739   if (!isFP) {
3740     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3741       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3742         // X > -1   -> X == 0, jump !sign.
3743         RHS = DAG.getConstant(0, RHS.getValueType());
3744         return X86::COND_NS;
3745       }
3746       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3747         // X < 0   -> X == 0, jump on sign.
3748         return X86::COND_S;
3749       }
3750       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3751         // X < 1   -> X <= 0
3752         RHS = DAG.getConstant(0, RHS.getValueType());
3753         return X86::COND_LE;
3754       }
3755     }
3756
3757     switch (SetCCOpcode) {
3758     default: llvm_unreachable("Invalid integer condition!");
3759     case ISD::SETEQ:  return X86::COND_E;
3760     case ISD::SETGT:  return X86::COND_G;
3761     case ISD::SETGE:  return X86::COND_GE;
3762     case ISD::SETLT:  return X86::COND_L;
3763     case ISD::SETLE:  return X86::COND_LE;
3764     case ISD::SETNE:  return X86::COND_NE;
3765     case ISD::SETULT: return X86::COND_B;
3766     case ISD::SETUGT: return X86::COND_A;
3767     case ISD::SETULE: return X86::COND_BE;
3768     case ISD::SETUGE: return X86::COND_AE;
3769     }
3770   }
3771
3772   // First determine if it is required or is profitable to flip the operands.
3773
3774   // If LHS is a foldable load, but RHS is not, flip the condition.
3775   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3776       !ISD::isNON_EXTLoad(RHS.getNode())) {
3777     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3778     std::swap(LHS, RHS);
3779   }
3780
3781   switch (SetCCOpcode) {
3782   default: break;
3783   case ISD::SETOLT:
3784   case ISD::SETOLE:
3785   case ISD::SETUGT:
3786   case ISD::SETUGE:
3787     std::swap(LHS, RHS);
3788     break;
3789   }
3790
3791   // On a floating point condition, the flags are set as follows:
3792   // ZF  PF  CF   op
3793   //  0 | 0 | 0 | X > Y
3794   //  0 | 0 | 1 | X < Y
3795   //  1 | 0 | 0 | X == Y
3796   //  1 | 1 | 1 | unordered
3797   switch (SetCCOpcode) {
3798   default: llvm_unreachable("Condcode should be pre-legalized away");
3799   case ISD::SETUEQ:
3800   case ISD::SETEQ:   return X86::COND_E;
3801   case ISD::SETOLT:              // flipped
3802   case ISD::SETOGT:
3803   case ISD::SETGT:   return X86::COND_A;
3804   case ISD::SETOLE:              // flipped
3805   case ISD::SETOGE:
3806   case ISD::SETGE:   return X86::COND_AE;
3807   case ISD::SETUGT:              // flipped
3808   case ISD::SETULT:
3809   case ISD::SETLT:   return X86::COND_B;
3810   case ISD::SETUGE:              // flipped
3811   case ISD::SETULE:
3812   case ISD::SETLE:   return X86::COND_BE;
3813   case ISD::SETONE:
3814   case ISD::SETNE:   return X86::COND_NE;
3815   case ISD::SETUO:   return X86::COND_P;
3816   case ISD::SETO:    return X86::COND_NP;
3817   case ISD::SETOEQ:
3818   case ISD::SETUNE:  return X86::COND_INVALID;
3819   }
3820 }
3821
3822 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3823 /// code. Current x86 isa includes the following FP cmov instructions:
3824 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3825 static bool hasFPCMov(unsigned X86CC) {
3826   switch (X86CC) {
3827   default:
3828     return false;
3829   case X86::COND_B:
3830   case X86::COND_BE:
3831   case X86::COND_E:
3832   case X86::COND_P:
3833   case X86::COND_A:
3834   case X86::COND_AE:
3835   case X86::COND_NE:
3836   case X86::COND_NP:
3837     return true;
3838   }
3839 }
3840
3841 /// isFPImmLegal - Returns true if the target can instruction select the
3842 /// specified FP immediate natively. If false, the legalizer will
3843 /// materialize the FP immediate as a load from a constant pool.
3844 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3845   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3846     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3847       return true;
3848   }
3849   return false;
3850 }
3851
3852 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3853                                               ISD::LoadExtType ExtTy,
3854                                               EVT NewVT) const {
3855   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3856   // relocation target a movq or addq instruction: don't let the load shrink.
3857   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3858   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3859     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3860       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3861   return true;
3862 }
3863
3864 /// \brief Returns true if it is beneficial to convert a load of a constant
3865 /// to just the constant itself.
3866 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3867                                                           Type *Ty) const {
3868   assert(Ty->isIntegerTy());
3869
3870   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3871   if (BitSize == 0 || BitSize > 64)
3872     return false;
3873   return true;
3874 }
3875
3876 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3877                                                 unsigned Index) const {
3878   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3879     return false;
3880
3881   return (Index == 0 || Index == ResVT.getVectorNumElements());
3882 }
3883
3884 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3885   // Speculate cttz only if we can directly use TZCNT.
3886   return Subtarget->hasBMI();
3887 }
3888
3889 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3890   // Speculate ctlz only if we can directly use LZCNT.
3891   return Subtarget->hasLZCNT();
3892 }
3893
3894 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3895 /// the specified range (L, H].
3896 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3897   return (Val < 0) || (Val >= Low && Val < Hi);
3898 }
3899
3900 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3901 /// specified value.
3902 static bool isUndefOrEqual(int Val, int CmpVal) {
3903   return (Val < 0 || Val == CmpVal);
3904 }
3905
3906 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3907 /// from position Pos and ending in Pos+Size, falls within the specified
3908 /// sequential range (Low, Low+Size]. or is undef.
3909 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3910                                        unsigned Pos, unsigned Size, int Low) {
3911   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3912     if (!isUndefOrEqual(Mask[i], Low))
3913       return false;
3914   return true;
3915 }
3916
3917 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3918 /// is suitable for input to PSHUFD. That is, it doesn't reference the other
3919 /// operand - by default will match for first operand.
3920 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT,
3921                          bool TestSecondOperand = false) {
3922   if (VT != MVT::v4f32 && VT != MVT::v4i32 &&
3923       VT != MVT::v2f64 && VT != MVT::v2i64)
3924     return false;
3925
3926   unsigned NumElems = VT.getVectorNumElements();
3927   unsigned Lo = TestSecondOperand ? NumElems : 0;
3928   unsigned Hi = Lo + NumElems;
3929
3930   for (unsigned i = 0; i < NumElems; ++i)
3931     if (!isUndefOrInRange(Mask[i], (int)Lo, (int)Hi))
3932       return false;
3933
3934   return true;
3935 }
3936
3937 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3938 /// is suitable for input to PSHUFHW.
3939 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3940   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3941     return false;
3942
3943   // Lower quadword copied in order or undef.
3944   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3945     return false;
3946
3947   // Upper quadword shuffled.
3948   for (unsigned i = 4; i != 8; ++i)
3949     if (!isUndefOrInRange(Mask[i], 4, 8))
3950       return false;
3951
3952   if (VT == MVT::v16i16) {
3953     // Lower quadword copied in order or undef.
3954     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3955       return false;
3956
3957     // Upper quadword shuffled.
3958     for (unsigned i = 12; i != 16; ++i)
3959       if (!isUndefOrInRange(Mask[i], 12, 16))
3960         return false;
3961   }
3962
3963   return true;
3964 }
3965
3966 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3967 /// is suitable for input to PSHUFLW.
3968 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3969   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3970     return false;
3971
3972   // Upper quadword copied in order.
3973   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3974     return false;
3975
3976   // Lower quadword shuffled.
3977   for (unsigned i = 0; i != 4; ++i)
3978     if (!isUndefOrInRange(Mask[i], 0, 4))
3979       return false;
3980
3981   if (VT == MVT::v16i16) {
3982     // Upper quadword copied in order.
3983     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3984       return false;
3985
3986     // Lower quadword shuffled.
3987     for (unsigned i = 8; i != 12; ++i)
3988       if (!isUndefOrInRange(Mask[i], 8, 12))
3989         return false;
3990   }
3991
3992   return true;
3993 }
3994
3995 /// \brief Return true if the mask specifies a shuffle of elements that is
3996 /// suitable for input to intralane (palignr) or interlane (valign) vector
3997 /// right-shift.
3998 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3999   unsigned NumElts = VT.getVectorNumElements();
4000   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
4001   unsigned NumLaneElts = NumElts/NumLanes;
4002
4003   // Do not handle 64-bit element shuffles with palignr.
4004   if (NumLaneElts == 2)
4005     return false;
4006
4007   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
4008     unsigned i;
4009     for (i = 0; i != NumLaneElts; ++i) {
4010       if (Mask[i+l] >= 0)
4011         break;
4012     }
4013
4014     // Lane is all undef, go to next lane
4015     if (i == NumLaneElts)
4016       continue;
4017
4018     int Start = Mask[i+l];
4019
4020     // Make sure its in this lane in one of the sources
4021     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
4022         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
4023       return false;
4024
4025     // If not lane 0, then we must match lane 0
4026     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
4027       return false;
4028
4029     // Correct second source to be contiguous with first source
4030     if (Start >= (int)NumElts)
4031       Start -= NumElts - NumLaneElts;
4032
4033     // Make sure we're shifting in the right direction.
4034     if (Start <= (int)(i+l))
4035       return false;
4036
4037     Start -= i;
4038
4039     // Check the rest of the elements to see if they are consecutive.
4040     for (++i; i != NumLaneElts; ++i) {
4041       int Idx = Mask[i+l];
4042
4043       // Make sure its in this lane
4044       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
4045           !isUndefOrInRange(Idx, 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(Idx, Mask[i]+l))
4050         return false;
4051
4052       if (Idx >= (int)NumElts)
4053         Idx -= NumElts - NumLaneElts;
4054
4055       if (!isUndefOrEqual(Idx, Start+i))
4056         return false;
4057
4058     }
4059   }
4060
4061   return true;
4062 }
4063
4064 /// \brief Return true if the node specifies a shuffle of elements that is
4065 /// suitable for input to PALIGNR.
4066 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4067                           const X86Subtarget *Subtarget) {
4068   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4069       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4070       VT.is512BitVector())
4071     // FIXME: Add AVX512BW.
4072     return false;
4073
4074   return isAlignrMask(Mask, VT, false);
4075 }
4076
4077 /// \brief Return true if the node specifies a shuffle of elements that is
4078 /// suitable for input to VALIGN.
4079 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4080                           const X86Subtarget *Subtarget) {
4081   // FIXME: Add AVX512VL.
4082   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4083     return false;
4084   return isAlignrMask(Mask, VT, true);
4085 }
4086
4087 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4088 /// the two vector operands have swapped position.
4089 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4090                                      unsigned NumElems) {
4091   for (unsigned i = 0; i != NumElems; ++i) {
4092     int idx = Mask[i];
4093     if (idx < 0)
4094       continue;
4095     else if (idx < (int)NumElems)
4096       Mask[i] = idx + NumElems;
4097     else
4098       Mask[i] = idx - NumElems;
4099   }
4100 }
4101
4102 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4103 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4104 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4105 /// reverse of what x86 shuffles want.
4106 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4107
4108   unsigned NumElems = VT.getVectorNumElements();
4109   unsigned NumLanes = VT.getSizeInBits()/128;
4110   unsigned NumLaneElems = NumElems/NumLanes;
4111
4112   if (NumLaneElems != 2 && NumLaneElems != 4)
4113     return false;
4114
4115   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4116   bool symetricMaskRequired =
4117     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4118
4119   // VSHUFPSY divides the resulting vector into 4 chunks.
4120   // The sources are also splitted into 4 chunks, and each destination
4121   // chunk must come from a different source chunk.
4122   //
4123   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4124   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4125   //
4126   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4127   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4128   //
4129   // VSHUFPDY divides the resulting vector into 4 chunks.
4130   // The sources are also splitted into 4 chunks, and each destination
4131   // chunk must come from a different source chunk.
4132   //
4133   //  SRC1 =>      X3       X2       X1       X0
4134   //  SRC2 =>      Y3       Y2       Y1       Y0
4135   //
4136   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4137   //
4138   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4139   unsigned HalfLaneElems = NumLaneElems/2;
4140   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4141     for (unsigned i = 0; i != NumLaneElems; ++i) {
4142       int Idx = Mask[i+l];
4143       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4144       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4145         return false;
4146       // For VSHUFPSY, the mask of the second half must be the same as the
4147       // first but with the appropriate offsets. This works in the same way as
4148       // VPERMILPS works with masks.
4149       if (!symetricMaskRequired || Idx < 0)
4150         continue;
4151       if (MaskVal[i] < 0) {
4152         MaskVal[i] = Idx - l;
4153         continue;
4154       }
4155       if ((signed)(Idx - l) != MaskVal[i])
4156         return false;
4157     }
4158   }
4159
4160   return true;
4161 }
4162
4163 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4164 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4165 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4166   if (!VT.is128BitVector())
4167     return false;
4168
4169   unsigned NumElems = VT.getVectorNumElements();
4170
4171   if (NumElems != 4)
4172     return false;
4173
4174   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4175   return isUndefOrEqual(Mask[0], 6) &&
4176          isUndefOrEqual(Mask[1], 7) &&
4177          isUndefOrEqual(Mask[2], 2) &&
4178          isUndefOrEqual(Mask[3], 3);
4179 }
4180
4181 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4182 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4183 /// <2, 3, 2, 3>
4184 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4185   if (!VT.is128BitVector())
4186     return false;
4187
4188   unsigned NumElems = VT.getVectorNumElements();
4189
4190   if (NumElems != 4)
4191     return false;
4192
4193   return isUndefOrEqual(Mask[0], 2) &&
4194          isUndefOrEqual(Mask[1], 3) &&
4195          isUndefOrEqual(Mask[2], 2) &&
4196          isUndefOrEqual(Mask[3], 3);
4197 }
4198
4199 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4200 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4201 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4202   if (!VT.is128BitVector())
4203     return false;
4204
4205   unsigned NumElems = VT.getVectorNumElements();
4206
4207   if (NumElems != 2 && NumElems != 4)
4208     return false;
4209
4210   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4211     if (!isUndefOrEqual(Mask[i], i + NumElems))
4212       return false;
4213
4214   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4215     if (!isUndefOrEqual(Mask[i], i))
4216       return false;
4217
4218   return true;
4219 }
4220
4221 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4222 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4223 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4224   if (!VT.is128BitVector())
4225     return false;
4226
4227   unsigned NumElems = VT.getVectorNumElements();
4228
4229   if (NumElems != 2 && NumElems != 4)
4230     return false;
4231
4232   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4233     if (!isUndefOrEqual(Mask[i], i))
4234       return false;
4235
4236   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4237     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4238       return false;
4239
4240   return true;
4241 }
4242
4243 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4244 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4245 /// i. e: If all but one element come from the same vector.
4246 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4247   // TODO: Deal with AVX's VINSERTPS
4248   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4249     return false;
4250
4251   unsigned CorrectPosV1 = 0;
4252   unsigned CorrectPosV2 = 0;
4253   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4254     if (Mask[i] == -1) {
4255       ++CorrectPosV1;
4256       ++CorrectPosV2;
4257       continue;
4258     }
4259
4260     if (Mask[i] == i)
4261       ++CorrectPosV1;
4262     else if (Mask[i] == i + 4)
4263       ++CorrectPosV2;
4264   }
4265
4266   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4267     // We have 3 elements (undefs count as elements from any vector) from one
4268     // vector, and one from another.
4269     return true;
4270
4271   return false;
4272 }
4273
4274 //
4275 // Some special combinations that can be optimized.
4276 //
4277 static
4278 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4279                                SelectionDAG &DAG) {
4280   MVT VT = SVOp->getSimpleValueType(0);
4281   SDLoc dl(SVOp);
4282
4283   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4284     return SDValue();
4285
4286   ArrayRef<int> Mask = SVOp->getMask();
4287
4288   // These are the special masks that may be optimized.
4289   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4290   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4291   bool MatchEvenMask = true;
4292   bool MatchOddMask  = true;
4293   for (int i=0; i<8; ++i) {
4294     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4295       MatchEvenMask = false;
4296     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4297       MatchOddMask = false;
4298   }
4299
4300   if (!MatchEvenMask && !MatchOddMask)
4301     return SDValue();
4302
4303   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4304
4305   SDValue Op0 = SVOp->getOperand(0);
4306   SDValue Op1 = SVOp->getOperand(1);
4307
4308   if (MatchEvenMask) {
4309     // Shift the second operand right to 32 bits.
4310     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4311     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4312   } else {
4313     // Shift the first operand left to 32 bits.
4314     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4315     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4316   }
4317   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4318   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4319 }
4320
4321 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4322 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4323 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4324                          bool HasInt256, bool V2IsSplat = false) {
4325
4326   assert(VT.getSizeInBits() >= 128 &&
4327          "Unsupported vector type for unpckl");
4328
4329   unsigned NumElts = VT.getVectorNumElements();
4330   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4331       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4332     return false;
4333
4334   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4335          "Unsupported vector type for unpckh");
4336
4337   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4338   unsigned NumLanes = VT.getSizeInBits()/128;
4339   unsigned NumLaneElts = NumElts/NumLanes;
4340
4341   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4342     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4343       int BitI  = Mask[l+i];
4344       int BitI1 = Mask[l+i+1];
4345       if (!isUndefOrEqual(BitI, j))
4346         return false;
4347       if (V2IsSplat) {
4348         if (!isUndefOrEqual(BitI1, NumElts))
4349           return false;
4350       } else {
4351         if (!isUndefOrEqual(BitI1, j + NumElts))
4352           return false;
4353       }
4354     }
4355   }
4356
4357   return true;
4358 }
4359
4360 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4361 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4362 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4363                          bool HasInt256, bool V2IsSplat = false) {
4364   assert(VT.getSizeInBits() >= 128 &&
4365          "Unsupported vector type for unpckh");
4366
4367   unsigned NumElts = VT.getVectorNumElements();
4368   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4369       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4370     return false;
4371
4372   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4373          "Unsupported vector type for unpckh");
4374
4375   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4376   unsigned NumLanes = VT.getSizeInBits()/128;
4377   unsigned NumLaneElts = NumElts/NumLanes;
4378
4379   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4380     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4381       int BitI  = Mask[l+i];
4382       int BitI1 = Mask[l+i+1];
4383       if (!isUndefOrEqual(BitI, j))
4384         return false;
4385       if (V2IsSplat) {
4386         if (isUndefOrEqual(BitI1, NumElts))
4387           return false;
4388       } else {
4389         if (!isUndefOrEqual(BitI1, j+NumElts))
4390           return false;
4391       }
4392     }
4393   }
4394   return true;
4395 }
4396
4397 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4398 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4399 /// <0, 0, 1, 1>
4400 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4401   unsigned NumElts = VT.getVectorNumElements();
4402   bool Is256BitVec = VT.is256BitVector();
4403
4404   if (VT.is512BitVector())
4405     return false;
4406   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4407          "Unsupported vector type for unpckh");
4408
4409   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4410       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4411     return false;
4412
4413   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4414   // FIXME: Need a better way to get rid of this, there's no latency difference
4415   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4416   // the former later. We should also remove the "_undef" special mask.
4417   if (NumElts == 4 && Is256BitVec)
4418     return false;
4419
4420   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4421   // independently on 128-bit lanes.
4422   unsigned NumLanes = VT.getSizeInBits()/128;
4423   unsigned NumLaneElts = NumElts/NumLanes;
4424
4425   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4426     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4427       int BitI  = Mask[l+i];
4428       int BitI1 = Mask[l+i+1];
4429
4430       if (!isUndefOrEqual(BitI, j))
4431         return false;
4432       if (!isUndefOrEqual(BitI1, j))
4433         return false;
4434     }
4435   }
4436
4437   return true;
4438 }
4439
4440 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4441 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4442 /// <2, 2, 3, 3>
4443 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4444   unsigned NumElts = VT.getVectorNumElements();
4445
4446   if (VT.is512BitVector())
4447     return false;
4448
4449   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4450          "Unsupported vector type for unpckh");
4451
4452   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4453       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4454     return false;
4455
4456   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4457   // independently on 128-bit lanes.
4458   unsigned NumLanes = VT.getSizeInBits()/128;
4459   unsigned NumLaneElts = NumElts/NumLanes;
4460
4461   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4462     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4463       int BitI  = Mask[l+i];
4464       int BitI1 = Mask[l+i+1];
4465       if (!isUndefOrEqual(BitI, j))
4466         return false;
4467       if (!isUndefOrEqual(BitI1, j))
4468         return false;
4469     }
4470   }
4471   return true;
4472 }
4473
4474 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4475 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4476 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4477   if (!VT.is512BitVector())
4478     return false;
4479
4480   unsigned NumElts = VT.getVectorNumElements();
4481   unsigned HalfSize = NumElts/2;
4482   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4483     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4484       *Imm = 1;
4485       return true;
4486     }
4487   }
4488   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4489     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4490       *Imm = 0;
4491       return true;
4492     }
4493   }
4494   return false;
4495 }
4496
4497 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4498 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4499 /// MOVSD, and MOVD, i.e. setting the lowest element.
4500 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4501   if (VT.getVectorElementType().getSizeInBits() < 32)
4502     return false;
4503   if (!VT.is128BitVector())
4504     return false;
4505
4506   unsigned NumElts = VT.getVectorNumElements();
4507
4508   if (!isUndefOrEqual(Mask[0], NumElts))
4509     return false;
4510
4511   for (unsigned i = 1; i != NumElts; ++i)
4512     if (!isUndefOrEqual(Mask[i], i))
4513       return false;
4514
4515   return true;
4516 }
4517
4518 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4519 /// as permutations between 128-bit chunks or halves. As an example: this
4520 /// shuffle bellow:
4521 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4522 /// The first half comes from the second half of V1 and the second half from the
4523 /// the second half of V2.
4524 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4525   if (!HasFp256 || !VT.is256BitVector())
4526     return false;
4527
4528   // The shuffle result is divided into half A and half B. In total the two
4529   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4530   // B must come from C, D, E or F.
4531   unsigned HalfSize = VT.getVectorNumElements()/2;
4532   bool MatchA = false, MatchB = false;
4533
4534   // Check if A comes from one of C, D, E, F.
4535   for (unsigned Half = 0; Half != 4; ++Half) {
4536     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4537       MatchA = true;
4538       break;
4539     }
4540   }
4541
4542   // Check if B comes from one of C, D, E, F.
4543   for (unsigned Half = 0; Half != 4; ++Half) {
4544     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4545       MatchB = true;
4546       break;
4547     }
4548   }
4549
4550   return MatchA && MatchB;
4551 }
4552
4553 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4554 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4555 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4556   MVT VT = SVOp->getSimpleValueType(0);
4557
4558   unsigned HalfSize = VT.getVectorNumElements()/2;
4559
4560   unsigned FstHalf = 0, SndHalf = 0;
4561   for (unsigned i = 0; i < HalfSize; ++i) {
4562     if (SVOp->getMaskElt(i) > 0) {
4563       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4564       break;
4565     }
4566   }
4567   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4568     if (SVOp->getMaskElt(i) > 0) {
4569       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4570       break;
4571     }
4572   }
4573
4574   return (FstHalf | (SndHalf << 4));
4575 }
4576
4577 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4578 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4579   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4580   if (EltSize < 32)
4581     return false;
4582
4583   unsigned NumElts = VT.getVectorNumElements();
4584   Imm8 = 0;
4585   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4586     for (unsigned i = 0; i != NumElts; ++i) {
4587       if (Mask[i] < 0)
4588         continue;
4589       Imm8 |= Mask[i] << (i*2);
4590     }
4591     return true;
4592   }
4593
4594   unsigned LaneSize = 4;
4595   SmallVector<int, 4> MaskVal(LaneSize, -1);
4596
4597   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4598     for (unsigned i = 0; i != LaneSize; ++i) {
4599       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4600         return false;
4601       if (Mask[i+l] < 0)
4602         continue;
4603       if (MaskVal[i] < 0) {
4604         MaskVal[i] = Mask[i+l] - l;
4605         Imm8 |= MaskVal[i] << (i*2);
4606         continue;
4607       }
4608       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4609         return false;
4610     }
4611   }
4612   return true;
4613 }
4614
4615 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4616 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4617 /// Note that VPERMIL mask matching is different depending whether theunderlying
4618 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4619 /// to the same elements of the low, but to the higher half of the source.
4620 /// In VPERMILPD the two lanes could be shuffled independently of each other
4621 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4622 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4623   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4624   if (VT.getSizeInBits() < 256 || EltSize < 32)
4625     return false;
4626   bool symetricMaskRequired = (EltSize == 32);
4627   unsigned NumElts = VT.getVectorNumElements();
4628
4629   unsigned NumLanes = VT.getSizeInBits()/128;
4630   unsigned LaneSize = NumElts/NumLanes;
4631   // 2 or 4 elements in one lane
4632
4633   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4634   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4635     for (unsigned i = 0; i != LaneSize; ++i) {
4636       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4637         return false;
4638       if (symetricMaskRequired) {
4639         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4640           ExpectedMaskVal[i] = Mask[i+l] - l;
4641           continue;
4642         }
4643         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4644           return false;
4645       }
4646     }
4647   }
4648   return true;
4649 }
4650
4651 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4652 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4653 /// element of vector 2 and the other elements to come from vector 1 in order.
4654 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4655                                bool V2IsSplat = false, bool V2IsUndef = false) {
4656   if (!VT.is128BitVector())
4657     return false;
4658
4659   unsigned NumOps = VT.getVectorNumElements();
4660   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4661     return false;
4662
4663   if (!isUndefOrEqual(Mask[0], 0))
4664     return false;
4665
4666   for (unsigned i = 1; i != NumOps; ++i)
4667     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4668           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4669           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4670       return false;
4671
4672   return true;
4673 }
4674
4675 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4676 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4677 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4678 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4679                            const X86Subtarget *Subtarget) {
4680   if (!Subtarget->hasSSE3())
4681     return false;
4682
4683   unsigned NumElems = VT.getVectorNumElements();
4684
4685   if ((VT.is128BitVector() && NumElems != 4) ||
4686       (VT.is256BitVector() && NumElems != 8) ||
4687       (VT.is512BitVector() && NumElems != 16))
4688     return false;
4689
4690   // "i+1" is the value the indexed mask element must have
4691   for (unsigned i = 0; i != NumElems; i += 2)
4692     if (!isUndefOrEqual(Mask[i], i+1) ||
4693         !isUndefOrEqual(Mask[i+1], i+1))
4694       return false;
4695
4696   return true;
4697 }
4698
4699 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4700 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4701 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4702 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4703                            const X86Subtarget *Subtarget) {
4704   if (!Subtarget->hasSSE3())
4705     return false;
4706
4707   unsigned NumElems = VT.getVectorNumElements();
4708
4709   if ((VT.is128BitVector() && NumElems != 4) ||
4710       (VT.is256BitVector() && NumElems != 8) ||
4711       (VT.is512BitVector() && NumElems != 16))
4712     return false;
4713
4714   // "i" is the value the indexed mask element must have
4715   for (unsigned i = 0; i != NumElems; i += 2)
4716     if (!isUndefOrEqual(Mask[i], i) ||
4717         !isUndefOrEqual(Mask[i+1], i))
4718       return false;
4719
4720   return true;
4721 }
4722
4723 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4724 /// specifies a shuffle of elements that is suitable for input to 256-bit
4725 /// version of MOVDDUP.
4726 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4727   if (!HasFp256 || !VT.is256BitVector())
4728     return false;
4729
4730   unsigned NumElts = VT.getVectorNumElements();
4731   if (NumElts != 4)
4732     return false;
4733
4734   for (unsigned i = 0; i != NumElts/2; ++i)
4735     if (!isUndefOrEqual(Mask[i], 0))
4736       return false;
4737   for (unsigned i = NumElts/2; i != NumElts; ++i)
4738     if (!isUndefOrEqual(Mask[i], NumElts/2))
4739       return false;
4740   return true;
4741 }
4742
4743 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4744 /// specifies a shuffle of elements that is suitable for input to 128-bit
4745 /// version of MOVDDUP.
4746 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4747   if (!VT.is128BitVector())
4748     return false;
4749
4750   unsigned e = VT.getVectorNumElements() / 2;
4751   for (unsigned i = 0; i != e; ++i)
4752     if (!isUndefOrEqual(Mask[i], i))
4753       return false;
4754   for (unsigned i = 0; i != e; ++i)
4755     if (!isUndefOrEqual(Mask[e+i], i))
4756       return false;
4757   return true;
4758 }
4759
4760 /// isVEXTRACTIndex - Return true if the specified
4761 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4762 /// suitable for instruction that extract 128 or 256 bit vectors
4763 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4764   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4765   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4766     return false;
4767
4768   // The index should be aligned on a vecWidth-bit boundary.
4769   uint64_t Index =
4770     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4771
4772   MVT VT = N->getSimpleValueType(0);
4773   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4774   bool Result = (Index * ElSize) % vecWidth == 0;
4775
4776   return Result;
4777 }
4778
4779 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4780 /// operand specifies a subvector insert that is suitable for input to
4781 /// insertion of 128 or 256-bit subvectors
4782 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4783   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4784   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4785     return false;
4786   // The index should be aligned on a vecWidth-bit boundary.
4787   uint64_t Index =
4788     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4789
4790   MVT VT = N->getSimpleValueType(0);
4791   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4792   bool Result = (Index * ElSize) % vecWidth == 0;
4793
4794   return Result;
4795 }
4796
4797 bool X86::isVINSERT128Index(SDNode *N) {
4798   return isVINSERTIndex(N, 128);
4799 }
4800
4801 bool X86::isVINSERT256Index(SDNode *N) {
4802   return isVINSERTIndex(N, 256);
4803 }
4804
4805 bool X86::isVEXTRACT128Index(SDNode *N) {
4806   return isVEXTRACTIndex(N, 128);
4807 }
4808
4809 bool X86::isVEXTRACT256Index(SDNode *N) {
4810   return isVEXTRACTIndex(N, 256);
4811 }
4812
4813 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4814 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4815 /// Handles 128-bit and 256-bit.
4816 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4817   MVT VT = N->getSimpleValueType(0);
4818
4819   assert((VT.getSizeInBits() >= 128) &&
4820          "Unsupported vector type for PSHUF/SHUFP");
4821
4822   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4823   // independently on 128-bit lanes.
4824   unsigned NumElts = VT.getVectorNumElements();
4825   unsigned NumLanes = VT.getSizeInBits()/128;
4826   unsigned NumLaneElts = NumElts/NumLanes;
4827
4828   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4829          "Only supports 2, 4 or 8 elements per lane");
4830
4831   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4832   unsigned Mask = 0;
4833   for (unsigned i = 0; i != NumElts; ++i) {
4834     int Elt = N->getMaskElt(i);
4835     if (Elt < 0) continue;
4836     Elt &= NumLaneElts - 1;
4837     unsigned ShAmt = (i << Shift) % 8;
4838     Mask |= Elt << ShAmt;
4839   }
4840
4841   return Mask;
4842 }
4843
4844 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4845 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4846 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4847   MVT VT = N->getSimpleValueType(0);
4848
4849   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4850          "Unsupported vector type for PSHUFHW");
4851
4852   unsigned NumElts = VT.getVectorNumElements();
4853
4854   unsigned Mask = 0;
4855   for (unsigned l = 0; l != NumElts; l += 8) {
4856     // 8 nodes per lane, but we only care about the last 4.
4857     for (unsigned i = 0; i < 4; ++i) {
4858       int Elt = N->getMaskElt(l+i+4);
4859       if (Elt < 0) continue;
4860       Elt &= 0x3; // only 2-bits.
4861       Mask |= Elt << (i * 2);
4862     }
4863   }
4864
4865   return Mask;
4866 }
4867
4868 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4869 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4870 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4871   MVT VT = N->getSimpleValueType(0);
4872
4873   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4874          "Unsupported vector type for PSHUFHW");
4875
4876   unsigned NumElts = VT.getVectorNumElements();
4877
4878   unsigned Mask = 0;
4879   for (unsigned l = 0; l != NumElts; l += 8) {
4880     // 8 nodes per lane, but we only care about the first 4.
4881     for (unsigned i = 0; i < 4; ++i) {
4882       int Elt = N->getMaskElt(l+i);
4883       if (Elt < 0) continue;
4884       Elt &= 0x3; // only 2-bits
4885       Mask |= Elt << (i * 2);
4886     }
4887   }
4888
4889   return Mask;
4890 }
4891
4892 /// \brief Return the appropriate immediate to shuffle the specified
4893 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4894 /// VALIGN (if Interlane is true) instructions.
4895 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4896                                            bool InterLane) {
4897   MVT VT = SVOp->getSimpleValueType(0);
4898   unsigned EltSize = InterLane ? 1 :
4899     VT.getVectorElementType().getSizeInBits() >> 3;
4900
4901   unsigned NumElts = VT.getVectorNumElements();
4902   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4903   unsigned NumLaneElts = NumElts/NumLanes;
4904
4905   int Val = 0;
4906   unsigned i;
4907   for (i = 0; i != NumElts; ++i) {
4908     Val = SVOp->getMaskElt(i);
4909     if (Val >= 0)
4910       break;
4911   }
4912   if (Val >= (int)NumElts)
4913     Val -= NumElts - NumLaneElts;
4914
4915   assert(Val - i > 0 && "PALIGNR imm should be positive");
4916   return (Val - i) * EltSize;
4917 }
4918
4919 /// \brief Return the appropriate immediate to shuffle the specified
4920 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4921 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4922   return getShuffleAlignrImmediate(SVOp, false);
4923 }
4924
4925 /// \brief Return the appropriate immediate to shuffle the specified
4926 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4927 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4928   return getShuffleAlignrImmediate(SVOp, true);
4929 }
4930
4931
4932 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4933   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4934   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4935     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4936
4937   uint64_t Index =
4938     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4939
4940   MVT VecVT = N->getOperand(0).getSimpleValueType();
4941   MVT ElVT = VecVT.getVectorElementType();
4942
4943   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4944   return Index / NumElemsPerChunk;
4945 }
4946
4947 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4948   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4949   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4950     llvm_unreachable("Illegal insert subvector for VINSERT");
4951
4952   uint64_t Index =
4953     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4954
4955   MVT VecVT = N->getSimpleValueType(0);
4956   MVT ElVT = VecVT.getVectorElementType();
4957
4958   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4959   return Index / NumElemsPerChunk;
4960 }
4961
4962 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4963 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4964 /// and VINSERTI128 instructions.
4965 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4966   return getExtractVEXTRACTImmediate(N, 128);
4967 }
4968
4969 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4970 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4971 /// and VINSERTI64x4 instructions.
4972 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4973   return getExtractVEXTRACTImmediate(N, 256);
4974 }
4975
4976 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4977 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4978 /// and VINSERTI128 instructions.
4979 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4980   return getInsertVINSERTImmediate(N, 128);
4981 }
4982
4983 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4984 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4985 /// and VINSERTI64x4 instructions.
4986 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4987   return getInsertVINSERTImmediate(N, 256);
4988 }
4989
4990 /// isZero - Returns true if Elt is a constant integer zero
4991 static bool isZero(SDValue V) {
4992   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4993   return C && C->isNullValue();
4994 }
4995
4996 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4997 /// constant +0.0.
4998 bool X86::isZeroNode(SDValue Elt) {
4999   if (isZero(Elt))
5000     return true;
5001   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
5002     return CFP->getValueAPF().isPosZero();
5003   return false;
5004 }
5005
5006 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
5007 /// match movhlps. The lower half elements should come from upper half of
5008 /// V1 (and in order), and the upper half elements should come from the upper
5009 /// half of V2 (and in order).
5010 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
5011   if (!VT.is128BitVector())
5012     return false;
5013   if (VT.getVectorNumElements() != 4)
5014     return false;
5015   for (unsigned i = 0, e = 2; i != e; ++i)
5016     if (!isUndefOrEqual(Mask[i], i+2))
5017       return false;
5018   for (unsigned i = 2; i != 4; ++i)
5019     if (!isUndefOrEqual(Mask[i], i+4))
5020       return false;
5021   return true;
5022 }
5023
5024 /// isScalarLoadToVector - Returns true if the node is a scalar load that
5025 /// is promoted to a vector. It also returns the LoadSDNode by reference if
5026 /// required.
5027 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
5028   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
5029     return false;
5030   N = N->getOperand(0).getNode();
5031   if (!ISD::isNON_EXTLoad(N))
5032     return false;
5033   if (LD)
5034     *LD = cast<LoadSDNode>(N);
5035   return true;
5036 }
5037
5038 // Test whether the given value is a vector value which will be legalized
5039 // into a load.
5040 static bool WillBeConstantPoolLoad(SDNode *N) {
5041   if (N->getOpcode() != ISD::BUILD_VECTOR)
5042     return false;
5043
5044   // Check for any non-constant elements.
5045   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5046     switch (N->getOperand(i).getNode()->getOpcode()) {
5047     case ISD::UNDEF:
5048     case ISD::ConstantFP:
5049     case ISD::Constant:
5050       break;
5051     default:
5052       return false;
5053     }
5054
5055   // Vectors of all-zeros and all-ones are materialized with special
5056   // instructions rather than being loaded.
5057   return !ISD::isBuildVectorAllZeros(N) &&
5058          !ISD::isBuildVectorAllOnes(N);
5059 }
5060
5061 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5062 /// match movlp{s|d}. The lower half elements should come from lower half of
5063 /// V1 (and in order), and the upper half elements should come from the upper
5064 /// half of V2 (and in order). And since V1 will become the source of the
5065 /// MOVLP, it must be either a vector load or a scalar load to vector.
5066 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5067                                ArrayRef<int> Mask, MVT VT) {
5068   if (!VT.is128BitVector())
5069     return false;
5070
5071   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5072     return false;
5073   // Is V2 is a vector load, don't do this transformation. We will try to use
5074   // load folding shufps op.
5075   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5076     return false;
5077
5078   unsigned NumElems = VT.getVectorNumElements();
5079
5080   if (NumElems != 2 && NumElems != 4)
5081     return false;
5082   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5083     if (!isUndefOrEqual(Mask[i], i))
5084       return false;
5085   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5086     if (!isUndefOrEqual(Mask[i], i+NumElems))
5087       return false;
5088   return true;
5089 }
5090
5091 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5092 /// to an zero vector.
5093 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5094 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5095   SDValue V1 = N->getOperand(0);
5096   SDValue V2 = N->getOperand(1);
5097   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5098   for (unsigned i = 0; i != NumElems; ++i) {
5099     int Idx = N->getMaskElt(i);
5100     if (Idx >= (int)NumElems) {
5101       unsigned Opc = V2.getOpcode();
5102       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5103         continue;
5104       if (Opc != ISD::BUILD_VECTOR ||
5105           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5106         return false;
5107     } else if (Idx >= 0) {
5108       unsigned Opc = V1.getOpcode();
5109       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5110         continue;
5111       if (Opc != ISD::BUILD_VECTOR ||
5112           !X86::isZeroNode(V1.getOperand(Idx)))
5113         return false;
5114     }
5115   }
5116   return true;
5117 }
5118
5119 /// getZeroVector - Returns a vector of specified type with all zero elements.
5120 ///
5121 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5122                              SelectionDAG &DAG, SDLoc dl) {
5123   assert(VT.isVector() && "Expected a vector type");
5124
5125   // Always build SSE zero vectors as <4 x i32> bitcasted
5126   // to their dest type. This ensures they get CSE'd.
5127   SDValue Vec;
5128   if (VT.is128BitVector()) {  // SSE
5129     if (Subtarget->hasSSE2()) {  // SSE2
5130       SDValue Cst = DAG.getConstant(0, MVT::i32);
5131       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5132     } else { // SSE1
5133       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5134       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5135     }
5136   } else if (VT.is256BitVector()) { // AVX
5137     if (Subtarget->hasInt256()) { // AVX2
5138       SDValue Cst = DAG.getConstant(0, MVT::i32);
5139       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5140       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5141     } else {
5142       // 256-bit logic and arithmetic instructions in AVX are all
5143       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5144       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5145       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5146       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5147     }
5148   } else if (VT.is512BitVector()) { // AVX-512
5149       SDValue Cst = DAG.getConstant(0, MVT::i32);
5150       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5151                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5152       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5153   } else if (VT.getScalarType() == MVT::i1) {
5154     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5155     SDValue Cst = DAG.getConstant(0, MVT::i1);
5156     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5157     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5158   } else
5159     llvm_unreachable("Unexpected vector type");
5160
5161   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5162 }
5163
5164 /// getOnesVector - Returns a vector of specified type with all bits set.
5165 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5166 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5167 /// Then bitcast to their original type, ensuring they get CSE'd.
5168 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5169                              SDLoc dl) {
5170   assert(VT.isVector() && "Expected a vector type");
5171
5172   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
5173   SDValue Vec;
5174   if (VT.is256BitVector()) {
5175     if (HasInt256) { // AVX2
5176       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5177       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5178     } else { // AVX
5179       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5180       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5181     }
5182   } else if (VT.is128BitVector()) {
5183     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5184   } else
5185     llvm_unreachable("Unexpected vector type");
5186
5187   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5188 }
5189
5190 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5191 /// that point to V2 points to its first element.
5192 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5193   for (unsigned i = 0; i != NumElems; ++i) {
5194     if (Mask[i] > (int)NumElems) {
5195       Mask[i] = NumElems;
5196     }
5197   }
5198 }
5199
5200 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5201 /// operation of specified width.
5202 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5203                        SDValue V2) {
5204   unsigned NumElems = VT.getVectorNumElements();
5205   SmallVector<int, 8> Mask;
5206   Mask.push_back(NumElems);
5207   for (unsigned i = 1; i != NumElems; ++i)
5208     Mask.push_back(i);
5209   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5210 }
5211
5212 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5213 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5214                           SDValue V2) {
5215   unsigned NumElems = VT.getVectorNumElements();
5216   SmallVector<int, 8> Mask;
5217   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5218     Mask.push_back(i);
5219     Mask.push_back(i + NumElems);
5220   }
5221   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5222 }
5223
5224 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5225 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5226                           SDValue V2) {
5227   unsigned NumElems = VT.getVectorNumElements();
5228   SmallVector<int, 8> Mask;
5229   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5230     Mask.push_back(i + Half);
5231     Mask.push_back(i + NumElems + Half);
5232   }
5233   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5234 }
5235
5236 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5237 // a generic shuffle instruction because the target has no such instructions.
5238 // Generate shuffles which repeat i16 and i8 several times until they can be
5239 // represented by v4f32 and then be manipulated by target suported shuffles.
5240 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5241   MVT VT = V.getSimpleValueType();
5242   int NumElems = VT.getVectorNumElements();
5243   SDLoc dl(V);
5244
5245   while (NumElems > 4) {
5246     if (EltNo < NumElems/2) {
5247       V = getUnpackl(DAG, dl, VT, V, V);
5248     } else {
5249       V = getUnpackh(DAG, dl, VT, V, V);
5250       EltNo -= NumElems/2;
5251     }
5252     NumElems >>= 1;
5253   }
5254   return V;
5255 }
5256
5257 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5258 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5259   MVT VT = V.getSimpleValueType();
5260   SDLoc dl(V);
5261
5262   if (VT.is128BitVector()) {
5263     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5264     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5265     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5266                              &SplatMask[0]);
5267   } else if (VT.is256BitVector()) {
5268     // To use VPERMILPS to splat scalars, the second half of indicies must
5269     // refer to the higher part, which is a duplication of the lower one,
5270     // because VPERMILPS can only handle in-lane permutations.
5271     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5272                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5273
5274     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5275     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5276                              &SplatMask[0]);
5277   } else
5278     llvm_unreachable("Vector size not supported");
5279
5280   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5281 }
5282
5283 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5284 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5285   MVT SrcVT = SV->getSimpleValueType(0);
5286   SDValue V1 = SV->getOperand(0);
5287   SDLoc dl(SV);
5288
5289   int EltNo = SV->getSplatIndex();
5290   int NumElems = SrcVT.getVectorNumElements();
5291   bool Is256BitVec = SrcVT.is256BitVector();
5292
5293   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5294          "Unknown how to promote splat for type");
5295
5296   // Extract the 128-bit part containing the splat element and update
5297   // the splat element index when it refers to the higher register.
5298   if (Is256BitVec) {
5299     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5300     if (EltNo >= NumElems/2)
5301       EltNo -= NumElems/2;
5302   }
5303
5304   // All i16 and i8 vector types can't be used directly by a generic shuffle
5305   // instruction because the target has no such instruction. Generate shuffles
5306   // which repeat i16 and i8 several times until they fit in i32, and then can
5307   // be manipulated by target suported shuffles.
5308   MVT EltVT = SrcVT.getVectorElementType();
5309   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5310     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5311
5312   // Recreate the 256-bit vector and place the same 128-bit vector
5313   // into the low and high part. This is necessary because we want
5314   // to use VPERM* to shuffle the vectors
5315   if (Is256BitVec) {
5316     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5317   }
5318
5319   return getLegalSplat(DAG, V1, EltNo);
5320 }
5321
5322 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5323 /// vector of zero or undef vector.  This produces a shuffle where the low
5324 /// element of V2 is swizzled into the zero/undef vector, landing at element
5325 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5326 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5327                                            bool IsZero,
5328                                            const X86Subtarget *Subtarget,
5329                                            SelectionDAG &DAG) {
5330   MVT VT = V2.getSimpleValueType();
5331   SDValue V1 = IsZero
5332     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5333   unsigned NumElems = VT.getVectorNumElements();
5334   SmallVector<int, 16> MaskVec;
5335   for (unsigned i = 0; i != NumElems; ++i)
5336     // If this is the insertion idx, put the low elt of V2 here.
5337     MaskVec.push_back(i == Idx ? NumElems : i);
5338   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5339 }
5340
5341 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5342 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5343 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5344 /// shuffles which use a single input multiple times, and in those cases it will
5345 /// adjust the mask to only have indices within that single input.
5346 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5347                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5348   unsigned NumElems = VT.getVectorNumElements();
5349   SDValue ImmN;
5350
5351   IsUnary = false;
5352   bool IsFakeUnary = false;
5353   switch(N->getOpcode()) {
5354   case X86ISD::BLENDI:
5355     ImmN = N->getOperand(N->getNumOperands()-1);
5356     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5357     break;
5358   case X86ISD::SHUFP:
5359     ImmN = N->getOperand(N->getNumOperands()-1);
5360     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5361     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5362     break;
5363   case X86ISD::UNPCKH:
5364     DecodeUNPCKHMask(VT, Mask);
5365     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5366     break;
5367   case X86ISD::UNPCKL:
5368     DecodeUNPCKLMask(VT, Mask);
5369     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5370     break;
5371   case X86ISD::MOVHLPS:
5372     DecodeMOVHLPSMask(NumElems, Mask);
5373     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5374     break;
5375   case X86ISD::MOVLHPS:
5376     DecodeMOVLHPSMask(NumElems, Mask);
5377     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5378     break;
5379   case X86ISD::PALIGNR:
5380     ImmN = N->getOperand(N->getNumOperands()-1);
5381     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5382     break;
5383   case X86ISD::PSHUFD:
5384   case X86ISD::VPERMILPI:
5385     ImmN = N->getOperand(N->getNumOperands()-1);
5386     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5387     IsUnary = true;
5388     break;
5389   case X86ISD::PSHUFHW:
5390     ImmN = N->getOperand(N->getNumOperands()-1);
5391     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5392     IsUnary = true;
5393     break;
5394   case X86ISD::PSHUFLW:
5395     ImmN = N->getOperand(N->getNumOperands()-1);
5396     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5397     IsUnary = true;
5398     break;
5399   case X86ISD::PSHUFB: {
5400     IsUnary = true;
5401     SDValue MaskNode = N->getOperand(1);
5402     while (MaskNode->getOpcode() == ISD::BITCAST)
5403       MaskNode = MaskNode->getOperand(0);
5404
5405     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5406       // If we have a build-vector, then things are easy.
5407       EVT VT = MaskNode.getValueType();
5408       assert(VT.isVector() &&
5409              "Can't produce a non-vector with a build_vector!");
5410       if (!VT.isInteger())
5411         return false;
5412
5413       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5414
5415       SmallVector<uint64_t, 32> RawMask;
5416       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5417         SDValue Op = MaskNode->getOperand(i);
5418         if (Op->getOpcode() == ISD::UNDEF) {
5419           RawMask.push_back((uint64_t)SM_SentinelUndef);
5420           continue;
5421         }
5422         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5423         if (!CN)
5424           return false;
5425         APInt MaskElement = CN->getAPIntValue();
5426
5427         // We now have to decode the element which could be any integer size and
5428         // extract each byte of it.
5429         for (int j = 0; j < NumBytesPerElement; ++j) {
5430           // Note that this is x86 and so always little endian: the low byte is
5431           // the first byte of the mask.
5432           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5433           MaskElement = MaskElement.lshr(8);
5434         }
5435       }
5436       DecodePSHUFBMask(RawMask, Mask);
5437       break;
5438     }
5439
5440     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5441     if (!MaskLoad)
5442       return false;
5443
5444     SDValue Ptr = MaskLoad->getBasePtr();
5445     if (Ptr->getOpcode() == X86ISD::Wrapper)
5446       Ptr = Ptr->getOperand(0);
5447
5448     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5449     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5450       return false;
5451
5452     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5453       // FIXME: Support AVX-512 here.
5454       Type *Ty = C->getType();
5455       if (!Ty->isVectorTy() || (Ty->getVectorNumElements() != 16 &&
5456                                 Ty->getVectorNumElements() != 32))
5457         return false;
5458
5459       DecodePSHUFBMask(C, Mask);
5460       break;
5461     }
5462
5463     return false;
5464   }
5465   case X86ISD::VPERMI:
5466     ImmN = N->getOperand(N->getNumOperands()-1);
5467     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5468     IsUnary = true;
5469     break;
5470   case X86ISD::MOVSS:
5471   case X86ISD::MOVSD: {
5472     // The index 0 always comes from the first element of the second source,
5473     // this is why MOVSS and MOVSD are used in the first place. The other
5474     // elements come from the other positions of the first source vector
5475     Mask.push_back(NumElems);
5476     for (unsigned i = 1; i != NumElems; ++i) {
5477       Mask.push_back(i);
5478     }
5479     break;
5480   }
5481   case X86ISD::VPERM2X128:
5482     ImmN = N->getOperand(N->getNumOperands()-1);
5483     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5484     if (Mask.empty()) return false;
5485     break;
5486   case X86ISD::MOVSLDUP:
5487     DecodeMOVSLDUPMask(VT, Mask);
5488     break;
5489   case X86ISD::MOVSHDUP:
5490     DecodeMOVSHDUPMask(VT, Mask);
5491     break;
5492   case X86ISD::MOVDDUP:
5493   case X86ISD::MOVLHPD:
5494   case X86ISD::MOVLPD:
5495   case X86ISD::MOVLPS:
5496     // Not yet implemented
5497     return false;
5498   default: llvm_unreachable("unknown target shuffle node");
5499   }
5500
5501   // If we have a fake unary shuffle, the shuffle mask is spread across two
5502   // inputs that are actually the same node. Re-map the mask to always point
5503   // into the first input.
5504   if (IsFakeUnary)
5505     for (int &M : Mask)
5506       if (M >= (int)Mask.size())
5507         M -= Mask.size();
5508
5509   return true;
5510 }
5511
5512 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5513 /// element of the result of the vector shuffle.
5514 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5515                                    unsigned Depth) {
5516   if (Depth == 6)
5517     return SDValue();  // Limit search depth.
5518
5519   SDValue V = SDValue(N, 0);
5520   EVT VT = V.getValueType();
5521   unsigned Opcode = V.getOpcode();
5522
5523   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5524   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5525     int Elt = SV->getMaskElt(Index);
5526
5527     if (Elt < 0)
5528       return DAG.getUNDEF(VT.getVectorElementType());
5529
5530     unsigned NumElems = VT.getVectorNumElements();
5531     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5532                                          : SV->getOperand(1);
5533     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5534   }
5535
5536   // Recurse into target specific vector shuffles to find scalars.
5537   if (isTargetShuffle(Opcode)) {
5538     MVT ShufVT = V.getSimpleValueType();
5539     unsigned NumElems = ShufVT.getVectorNumElements();
5540     SmallVector<int, 16> ShuffleMask;
5541     bool IsUnary;
5542
5543     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5544       return SDValue();
5545
5546     int Elt = ShuffleMask[Index];
5547     if (Elt < 0)
5548       return DAG.getUNDEF(ShufVT.getVectorElementType());
5549
5550     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5551                                          : N->getOperand(1);
5552     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5553                                Depth+1);
5554   }
5555
5556   // Actual nodes that may contain scalar elements
5557   if (Opcode == ISD::BITCAST) {
5558     V = V.getOperand(0);
5559     EVT SrcVT = V.getValueType();
5560     unsigned NumElems = VT.getVectorNumElements();
5561
5562     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5563       return SDValue();
5564   }
5565
5566   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5567     return (Index == 0) ? V.getOperand(0)
5568                         : DAG.getUNDEF(VT.getVectorElementType());
5569
5570   if (V.getOpcode() == ISD::BUILD_VECTOR)
5571     return V.getOperand(Index);
5572
5573   return SDValue();
5574 }
5575
5576 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5577 /// shuffle operation which come from a consecutively from a zero. The
5578 /// search can start in two different directions, from left or right.
5579 /// We count undefs as zeros until PreferredNum is reached.
5580 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5581                                          unsigned NumElems, bool ZerosFromLeft,
5582                                          SelectionDAG &DAG,
5583                                          unsigned PreferredNum = -1U) {
5584   unsigned NumZeros = 0;
5585   for (unsigned i = 0; i != NumElems; ++i) {
5586     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5587     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5588     if (!Elt.getNode())
5589       break;
5590
5591     if (X86::isZeroNode(Elt))
5592       ++NumZeros;
5593     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5594       NumZeros = std::min(NumZeros + 1, PreferredNum);
5595     else
5596       break;
5597   }
5598
5599   return NumZeros;
5600 }
5601
5602 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5603 /// correspond consecutively to elements from one of the vector operands,
5604 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5605 static
5606 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5607                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5608                               unsigned NumElems, unsigned &OpNum) {
5609   bool SeenV1 = false;
5610   bool SeenV2 = false;
5611
5612   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5613     int Idx = SVOp->getMaskElt(i);
5614     // Ignore undef indicies
5615     if (Idx < 0)
5616       continue;
5617
5618     if (Idx < (int)NumElems)
5619       SeenV1 = true;
5620     else
5621       SeenV2 = true;
5622
5623     // Only accept consecutive elements from the same vector
5624     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5625       return false;
5626   }
5627
5628   OpNum = SeenV1 ? 0 : 1;
5629   return true;
5630 }
5631
5632 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5633 /// logical left shift of a vector.
5634 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5635                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5636   unsigned NumElems =
5637     SVOp->getSimpleValueType(0).getVectorNumElements();
5638   unsigned NumZeros = getNumOfConsecutiveZeros(
5639       SVOp, NumElems, false /* check zeros from right */, DAG,
5640       SVOp->getMaskElt(0));
5641   unsigned OpSrc;
5642
5643   if (!NumZeros)
5644     return false;
5645
5646   // Considering the elements in the mask that are not consecutive zeros,
5647   // check if they consecutively come from only one of the source vectors.
5648   //
5649   //               V1 = {X, A, B, C}     0
5650   //                         \  \  \    /
5651   //   vector_shuffle V1, V2 <1, 2, 3, X>
5652   //
5653   if (!isShuffleMaskConsecutive(SVOp,
5654             0,                   // Mask Start Index
5655             NumElems-NumZeros,   // Mask End Index(exclusive)
5656             NumZeros,            // Where to start looking in the src vector
5657             NumElems,            // Number of elements in vector
5658             OpSrc))              // Which source operand ?
5659     return false;
5660
5661   isLeft = false;
5662   ShAmt = NumZeros;
5663   ShVal = SVOp->getOperand(OpSrc);
5664   return true;
5665 }
5666
5667 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5668 /// logical left shift of a vector.
5669 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5670                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5671   unsigned NumElems =
5672     SVOp->getSimpleValueType(0).getVectorNumElements();
5673   unsigned NumZeros = getNumOfConsecutiveZeros(
5674       SVOp, NumElems, true /* check zeros from left */, DAG,
5675       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5676   unsigned OpSrc;
5677
5678   if (!NumZeros)
5679     return false;
5680
5681   // Considering the elements in the mask that are not consecutive zeros,
5682   // check if they consecutively come from only one of the source vectors.
5683   //
5684   //                           0    { A, B, X, X } = V2
5685   //                          / \    /  /
5686   //   vector_shuffle V1, V2 <X, X, 4, 5>
5687   //
5688   if (!isShuffleMaskConsecutive(SVOp,
5689             NumZeros,     // Mask Start Index
5690             NumElems,     // Mask End Index(exclusive)
5691             0,            // Where to start looking in the src vector
5692             NumElems,     // Number of elements in vector
5693             OpSrc))       // Which source operand ?
5694     return false;
5695
5696   isLeft = true;
5697   ShAmt = NumZeros;
5698   ShVal = SVOp->getOperand(OpSrc);
5699   return true;
5700 }
5701
5702 /// isVectorShift - Returns true if the shuffle can be implemented as a
5703 /// logical left or right shift of a vector.
5704 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5705                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5706   // Although the logic below support any bitwidth size, there are no
5707   // shift instructions which handle more than 128-bit vectors.
5708   if (!SVOp->getSimpleValueType(0).is128BitVector())
5709     return false;
5710
5711   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5712       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5713     return true;
5714
5715   return false;
5716 }
5717
5718 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5719 ///
5720 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5721                                        unsigned NumNonZero, unsigned NumZero,
5722                                        SelectionDAG &DAG,
5723                                        const X86Subtarget* Subtarget,
5724                                        const TargetLowering &TLI) {
5725   if (NumNonZero > 8)
5726     return SDValue();
5727
5728   SDLoc dl(Op);
5729   SDValue V;
5730   bool First = true;
5731   for (unsigned i = 0; i < 16; ++i) {
5732     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5733     if (ThisIsNonZero && First) {
5734       if (NumZero)
5735         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5736       else
5737         V = DAG.getUNDEF(MVT::v8i16);
5738       First = false;
5739     }
5740
5741     if ((i & 1) != 0) {
5742       SDValue ThisElt, LastElt;
5743       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5744       if (LastIsNonZero) {
5745         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5746                               MVT::i16, Op.getOperand(i-1));
5747       }
5748       if (ThisIsNonZero) {
5749         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5750         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5751                               ThisElt, DAG.getConstant(8, MVT::i8));
5752         if (LastIsNonZero)
5753           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5754       } else
5755         ThisElt = LastElt;
5756
5757       if (ThisElt.getNode())
5758         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5759                         DAG.getIntPtrConstant(i/2));
5760     }
5761   }
5762
5763   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5764 }
5765
5766 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5767 ///
5768 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5769                                      unsigned NumNonZero, unsigned NumZero,
5770                                      SelectionDAG &DAG,
5771                                      const X86Subtarget* Subtarget,
5772                                      const TargetLowering &TLI) {
5773   if (NumNonZero > 4)
5774     return SDValue();
5775
5776   SDLoc dl(Op);
5777   SDValue V;
5778   bool First = true;
5779   for (unsigned i = 0; i < 8; ++i) {
5780     bool isNonZero = (NonZeros & (1 << i)) != 0;
5781     if (isNonZero) {
5782       if (First) {
5783         if (NumZero)
5784           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5785         else
5786           V = DAG.getUNDEF(MVT::v8i16);
5787         First = false;
5788       }
5789       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5790                       MVT::v8i16, V, Op.getOperand(i),
5791                       DAG.getIntPtrConstant(i));
5792     }
5793   }
5794
5795   return V;
5796 }
5797
5798 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5799 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5800                                      const X86Subtarget *Subtarget,
5801                                      const TargetLowering &TLI) {
5802   // Find all zeroable elements.
5803   bool Zeroable[4];
5804   for (int i=0; i < 4; ++i) {
5805     SDValue Elt = Op->getOperand(i);
5806     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5807   }
5808   assert(std::count_if(&Zeroable[0], &Zeroable[4],
5809                        [](bool M) { return !M; }) > 1 &&
5810          "We expect at least two non-zero elements!");
5811
5812   // We only know how to deal with build_vector nodes where elements are either
5813   // zeroable or extract_vector_elt with constant index.
5814   SDValue FirstNonZero;
5815   unsigned FirstNonZeroIdx;
5816   for (unsigned i=0; i < 4; ++i) {
5817     if (Zeroable[i])
5818       continue;
5819     SDValue Elt = Op->getOperand(i);
5820     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5821         !isa<ConstantSDNode>(Elt.getOperand(1)))
5822       return SDValue();
5823     // Make sure that this node is extracting from a 128-bit vector.
5824     MVT VT = Elt.getOperand(0).getSimpleValueType();
5825     if (!VT.is128BitVector())
5826       return SDValue();
5827     if (!FirstNonZero.getNode()) {
5828       FirstNonZero = Elt;
5829       FirstNonZeroIdx = i;
5830     }
5831   }
5832
5833   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5834   SDValue V1 = FirstNonZero.getOperand(0);
5835   MVT VT = V1.getSimpleValueType();
5836
5837   // See if this build_vector can be lowered as a blend with zero.
5838   SDValue Elt;
5839   unsigned EltMaskIdx, EltIdx;
5840   int Mask[4];
5841   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5842     if (Zeroable[EltIdx]) {
5843       // The zero vector will be on the right hand side.
5844       Mask[EltIdx] = EltIdx+4;
5845       continue;
5846     }
5847
5848     Elt = Op->getOperand(EltIdx);
5849     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5850     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5851     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5852       break;
5853     Mask[EltIdx] = EltIdx;
5854   }
5855
5856   if (EltIdx == 4) {
5857     // Let the shuffle legalizer deal with blend operations.
5858     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5859     if (V1.getSimpleValueType() != VT)
5860       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5861     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5862   }
5863
5864   // See if we can lower this build_vector to a INSERTPS.
5865   if (!Subtarget->hasSSE41())
5866     return SDValue();
5867
5868   SDValue V2 = Elt.getOperand(0);
5869   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5870     V1 = SDValue();
5871
5872   bool CanFold = true;
5873   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5874     if (Zeroable[i])
5875       continue;
5876
5877     SDValue Current = Op->getOperand(i);
5878     SDValue SrcVector = Current->getOperand(0);
5879     if (!V1.getNode())
5880       V1 = SrcVector;
5881     CanFold = SrcVector == V1 &&
5882       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5883   }
5884
5885   if (!CanFold)
5886     return SDValue();
5887
5888   assert(V1.getNode() && "Expected at least two non-zero elements!");
5889   if (V1.getSimpleValueType() != MVT::v4f32)
5890     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5891   if (V2.getSimpleValueType() != MVT::v4f32)
5892     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5893
5894   // Ok, we can emit an INSERTPS instruction.
5895   unsigned ZMask = 0;
5896   for (int i = 0; i < 4; ++i)
5897     if (Zeroable[i])
5898       ZMask |= 1 << i;
5899
5900   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5901   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5902   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
5903                                DAG.getIntPtrConstant(InsertPSMask));
5904   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
5905 }
5906
5907 /// getVShift - Return a vector logical shift node.
5908 ///
5909 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5910                          unsigned NumBits, SelectionDAG &DAG,
5911                          const TargetLowering &TLI, SDLoc dl) {
5912   assert(VT.is128BitVector() && "Unknown type for VShift");
5913   EVT ShVT = MVT::v2i64;
5914   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5915   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5916   return DAG.getNode(ISD::BITCAST, dl, VT,
5917                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5918                              DAG.getConstant(NumBits,
5919                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5920 }
5921
5922 static SDValue
5923 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5924
5925   // Check if the scalar load can be widened into a vector load. And if
5926   // the address is "base + cst" see if the cst can be "absorbed" into
5927   // the shuffle mask.
5928   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5929     SDValue Ptr = LD->getBasePtr();
5930     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5931       return SDValue();
5932     EVT PVT = LD->getValueType(0);
5933     if (PVT != MVT::i32 && PVT != MVT::f32)
5934       return SDValue();
5935
5936     int FI = -1;
5937     int64_t Offset = 0;
5938     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5939       FI = FINode->getIndex();
5940       Offset = 0;
5941     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5942                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5943       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5944       Offset = Ptr.getConstantOperandVal(1);
5945       Ptr = Ptr.getOperand(0);
5946     } else {
5947       return SDValue();
5948     }
5949
5950     // FIXME: 256-bit vector instructions don't require a strict alignment,
5951     // improve this code to support it better.
5952     unsigned RequiredAlign = VT.getSizeInBits()/8;
5953     SDValue Chain = LD->getChain();
5954     // Make sure the stack object alignment is at least 16 or 32.
5955     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5956     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5957       if (MFI->isFixedObjectIndex(FI)) {
5958         // Can't change the alignment. FIXME: It's possible to compute
5959         // the exact stack offset and reference FI + adjust offset instead.
5960         // If someone *really* cares about this. That's the way to implement it.
5961         return SDValue();
5962       } else {
5963         MFI->setObjectAlignment(FI, RequiredAlign);
5964       }
5965     }
5966
5967     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5968     // Ptr + (Offset & ~15).
5969     if (Offset < 0)
5970       return SDValue();
5971     if ((Offset % RequiredAlign) & 3)
5972       return SDValue();
5973     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5974     if (StartOffset)
5975       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5976                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5977
5978     int EltNo = (Offset - StartOffset) >> 2;
5979     unsigned NumElems = VT.getVectorNumElements();
5980
5981     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5982     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5983                              LD->getPointerInfo().getWithOffset(StartOffset),
5984                              false, false, false, 0);
5985
5986     SmallVector<int, 8> Mask;
5987     for (unsigned i = 0; i != NumElems; ++i)
5988       Mask.push_back(EltNo);
5989
5990     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5991   }
5992
5993   return SDValue();
5994 }
5995
5996 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5997 /// vector of type 'VT', see if the elements can be replaced by a single large
5998 /// load which has the same value as a build_vector whose operands are 'elts'.
5999 ///
6000 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
6001 ///
6002 /// FIXME: we'd also like to handle the case where the last elements are zero
6003 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
6004 /// There's even a handy isZeroNode for that purpose.
6005 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
6006                                         SDLoc &DL, SelectionDAG &DAG,
6007                                         bool isAfterLegalize) {
6008   EVT EltVT = VT.getVectorElementType();
6009   unsigned NumElems = Elts.size();
6010
6011   LoadSDNode *LDBase = nullptr;
6012   unsigned LastLoadedElt = -1U;
6013
6014   // For each element in the initializer, see if we've found a load or an undef.
6015   // If we don't find an initial load element, or later load elements are
6016   // non-consecutive, bail out.
6017   for (unsigned i = 0; i < NumElems; ++i) {
6018     SDValue Elt = Elts[i];
6019
6020     if (!Elt.getNode() ||
6021         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
6022       return SDValue();
6023     if (!LDBase) {
6024       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
6025         return SDValue();
6026       LDBase = cast<LoadSDNode>(Elt.getNode());
6027       LastLoadedElt = i;
6028       continue;
6029     }
6030     if (Elt.getOpcode() == ISD::UNDEF)
6031       continue;
6032
6033     LoadSDNode *LD = cast<LoadSDNode>(Elt);
6034     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
6035       return SDValue();
6036     LastLoadedElt = i;
6037   }
6038
6039   // If we have found an entire vector of loads and undefs, then return a large
6040   // load of the entire vector width starting at the base pointer.  If we found
6041   // consecutive loads for the low half, generate a vzext_load node.
6042   if (LastLoadedElt == NumElems - 1) {
6043
6044     if (isAfterLegalize &&
6045         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
6046       return SDValue();
6047
6048     SDValue NewLd = SDValue();
6049
6050     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6051                         LDBase->getPointerInfo(), LDBase->isVolatile(),
6052                         LDBase->isNonTemporal(), LDBase->isInvariant(),
6053                         LDBase->getAlignment());
6054
6055     if (LDBase->hasAnyUseOfValue(1)) {
6056       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6057                                      SDValue(LDBase, 1),
6058                                      SDValue(NewLd.getNode(), 1));
6059       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6060       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6061                              SDValue(NewLd.getNode(), 1));
6062     }
6063
6064     return NewLd;
6065   }
6066
6067   //TODO: The code below fires only for for loading the low v2i32 / v2f32
6068   //of a v4i32 / v4f32. It's probably worth generalizing.
6069   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
6070       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
6071     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
6072     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
6073     SDValue ResNode =
6074         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
6075                                 LDBase->getPointerInfo(),
6076                                 LDBase->getAlignment(),
6077                                 false/*isVolatile*/, true/*ReadMem*/,
6078                                 false/*WriteMem*/);
6079
6080     // Make sure the newly-created LOAD is in the same position as LDBase in
6081     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
6082     // update uses of LDBase's output chain to use the TokenFactor.
6083     if (LDBase->hasAnyUseOfValue(1)) {
6084       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6085                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
6086       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6087       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6088                              SDValue(ResNode.getNode(), 1));
6089     }
6090
6091     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
6092   }
6093   return SDValue();
6094 }
6095
6096 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6097 /// to generate a splat value for the following cases:
6098 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6099 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6100 /// a scalar load, or a constant.
6101 /// The VBROADCAST node is returned when a pattern is found,
6102 /// or SDValue() otherwise.
6103 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6104                                     SelectionDAG &DAG) {
6105   // VBROADCAST requires AVX.
6106   // TODO: Splats could be generated for non-AVX CPUs using SSE
6107   // instructions, but there's less potential gain for only 128-bit vectors.
6108   if (!Subtarget->hasAVX())
6109     return SDValue();
6110
6111   MVT VT = Op.getSimpleValueType();
6112   SDLoc dl(Op);
6113
6114   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6115          "Unsupported vector type for broadcast.");
6116
6117   SDValue Ld;
6118   bool ConstSplatVal;
6119
6120   switch (Op.getOpcode()) {
6121     default:
6122       // Unknown pattern found.
6123       return SDValue();
6124
6125     case ISD::BUILD_VECTOR: {
6126       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6127       BitVector UndefElements;
6128       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6129
6130       // We need a splat of a single value to use broadcast, and it doesn't
6131       // make any sense if the value is only in one element of the vector.
6132       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6133         return SDValue();
6134
6135       Ld = Splat;
6136       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6137                        Ld.getOpcode() == ISD::ConstantFP);
6138
6139       // Make sure that all of the users of a non-constant load are from the
6140       // BUILD_VECTOR node.
6141       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6142         return SDValue();
6143       break;
6144     }
6145
6146     case ISD::VECTOR_SHUFFLE: {
6147       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6148
6149       // Shuffles must have a splat mask where the first element is
6150       // broadcasted.
6151       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6152         return SDValue();
6153
6154       SDValue Sc = Op.getOperand(0);
6155       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6156           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6157
6158         if (!Subtarget->hasInt256())
6159           return SDValue();
6160
6161         // Use the register form of the broadcast instruction available on AVX2.
6162         if (VT.getSizeInBits() >= 256)
6163           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6164         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6165       }
6166
6167       Ld = Sc.getOperand(0);
6168       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6169                        Ld.getOpcode() == ISD::ConstantFP);
6170
6171       // The scalar_to_vector node and the suspected
6172       // load node must have exactly one user.
6173       // Constants may have multiple users.
6174
6175       // AVX-512 has register version of the broadcast
6176       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6177         Ld.getValueType().getSizeInBits() >= 32;
6178       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6179           !hasRegVer))
6180         return SDValue();
6181       break;
6182     }
6183   }
6184
6185   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6186   bool IsGE256 = (VT.getSizeInBits() >= 256);
6187
6188   // When optimizing for size, generate up to 5 extra bytes for a broadcast
6189   // instruction to save 8 or more bytes of constant pool data.
6190   // TODO: If multiple splats are generated to load the same constant,
6191   // it may be detrimental to overall size. There needs to be a way to detect
6192   // that condition to know if this is truly a size win.
6193   const Function *F = DAG.getMachineFunction().getFunction();
6194   bool OptForSize = F->getAttributes().
6195     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6196
6197   // Handle broadcasting a single constant scalar from the constant pool
6198   // into a vector.
6199   // On Sandybridge (no AVX2), it is still better to load a constant vector
6200   // from the constant pool and not to broadcast it from a scalar.
6201   // But override that restriction when optimizing for size.
6202   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6203   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
6204     EVT CVT = Ld.getValueType();
6205     assert(!CVT.isVector() && "Must not broadcast a vector type");
6206
6207     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6208     // For size optimization, also splat v2f64 and v2i64, and for size opt
6209     // with AVX2, also splat i8 and i16.
6210     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6211     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6212         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
6213       const Constant *C = nullptr;
6214       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6215         C = CI->getConstantIntValue();
6216       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6217         C = CF->getConstantFPValue();
6218
6219       assert(C && "Invalid constant type");
6220
6221       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6222       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6223       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6224       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6225                        MachinePointerInfo::getConstantPool(),
6226                        false, false, false, Alignment);
6227
6228       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6229     }
6230   }
6231
6232   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6233
6234   // Handle AVX2 in-register broadcasts.
6235   if (!IsLoad && Subtarget->hasInt256() &&
6236       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6237     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6238
6239   // The scalar source must be a normal load.
6240   if (!IsLoad)
6241     return SDValue();
6242
6243   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6244       (Subtarget->hasVLX() && ScalarSize == 64))
6245     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6246
6247   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6248   // double since there is no vbroadcastsd xmm
6249   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6250     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6251       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6252   }
6253
6254   // Unsupported broadcast.
6255   return SDValue();
6256 }
6257
6258 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6259 /// underlying vector and index.
6260 ///
6261 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6262 /// index.
6263 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6264                                          SDValue ExtIdx) {
6265   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6266   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6267     return Idx;
6268
6269   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6270   // lowered this:
6271   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6272   // to:
6273   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6274   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6275   //                           undef)
6276   //                       Constant<0>)
6277   // In this case the vector is the extract_subvector expression and the index
6278   // is 2, as specified by the shuffle.
6279   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6280   SDValue ShuffleVec = SVOp->getOperand(0);
6281   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6282   assert(ShuffleVecVT.getVectorElementType() ==
6283          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6284
6285   int ShuffleIdx = SVOp->getMaskElt(Idx);
6286   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6287     ExtractedFromVec = ShuffleVec;
6288     return ShuffleIdx;
6289   }
6290   return Idx;
6291 }
6292
6293 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6294   MVT VT = Op.getSimpleValueType();
6295
6296   // Skip if insert_vec_elt is not supported.
6297   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6298   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6299     return SDValue();
6300
6301   SDLoc DL(Op);
6302   unsigned NumElems = Op.getNumOperands();
6303
6304   SDValue VecIn1;
6305   SDValue VecIn2;
6306   SmallVector<unsigned, 4> InsertIndices;
6307   SmallVector<int, 8> Mask(NumElems, -1);
6308
6309   for (unsigned i = 0; i != NumElems; ++i) {
6310     unsigned Opc = Op.getOperand(i).getOpcode();
6311
6312     if (Opc == ISD::UNDEF)
6313       continue;
6314
6315     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6316       // Quit if more than 1 elements need inserting.
6317       if (InsertIndices.size() > 1)
6318         return SDValue();
6319
6320       InsertIndices.push_back(i);
6321       continue;
6322     }
6323
6324     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6325     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6326     // Quit if non-constant index.
6327     if (!isa<ConstantSDNode>(ExtIdx))
6328       return SDValue();
6329     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6330
6331     // Quit if extracted from vector of different type.
6332     if (ExtractedFromVec.getValueType() != VT)
6333       return SDValue();
6334
6335     if (!VecIn1.getNode())
6336       VecIn1 = ExtractedFromVec;
6337     else if (VecIn1 != ExtractedFromVec) {
6338       if (!VecIn2.getNode())
6339         VecIn2 = ExtractedFromVec;
6340       else if (VecIn2 != ExtractedFromVec)
6341         // Quit if more than 2 vectors to shuffle
6342         return SDValue();
6343     }
6344
6345     if (ExtractedFromVec == VecIn1)
6346       Mask[i] = Idx;
6347     else if (ExtractedFromVec == VecIn2)
6348       Mask[i] = Idx + NumElems;
6349   }
6350
6351   if (!VecIn1.getNode())
6352     return SDValue();
6353
6354   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6355   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6356   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6357     unsigned Idx = InsertIndices[i];
6358     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6359                      DAG.getIntPtrConstant(Idx));
6360   }
6361
6362   return NV;
6363 }
6364
6365 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6366 SDValue
6367 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6368
6369   MVT VT = Op.getSimpleValueType();
6370   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6371          "Unexpected type in LowerBUILD_VECTORvXi1!");
6372
6373   SDLoc dl(Op);
6374   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6375     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6376     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6377     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6378   }
6379
6380   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6381     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6382     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6383     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6384   }
6385
6386   bool AllContants = true;
6387   uint64_t Immediate = 0;
6388   int NonConstIdx = -1;
6389   bool IsSplat = true;
6390   unsigned NumNonConsts = 0;
6391   unsigned NumConsts = 0;
6392   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6393     SDValue In = Op.getOperand(idx);
6394     if (In.getOpcode() == ISD::UNDEF)
6395       continue;
6396     if (!isa<ConstantSDNode>(In)) {
6397       AllContants = false;
6398       NonConstIdx = idx;
6399       NumNonConsts++;
6400     } else {
6401       NumConsts++;
6402       if (cast<ConstantSDNode>(In)->getZExtValue())
6403       Immediate |= (1ULL << idx);
6404     }
6405     if (In != Op.getOperand(0))
6406       IsSplat = false;
6407   }
6408
6409   if (AllContants) {
6410     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6411       DAG.getConstant(Immediate, MVT::i16));
6412     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6413                        DAG.getIntPtrConstant(0));
6414   }
6415
6416   if (NumNonConsts == 1 && NonConstIdx != 0) {
6417     SDValue DstVec;
6418     if (NumConsts) {
6419       SDValue VecAsImm = DAG.getConstant(Immediate,
6420                                          MVT::getIntegerVT(VT.getSizeInBits()));
6421       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6422     }
6423     else
6424       DstVec = DAG.getUNDEF(VT);
6425     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6426                        Op.getOperand(NonConstIdx),
6427                        DAG.getIntPtrConstant(NonConstIdx));
6428   }
6429   if (!IsSplat && (NonConstIdx != 0))
6430     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6431   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6432   SDValue Select;
6433   if (IsSplat)
6434     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6435                           DAG.getConstant(-1, SelectVT),
6436                           DAG.getConstant(0, SelectVT));
6437   else
6438     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6439                          DAG.getConstant((Immediate | 1), SelectVT),
6440                          DAG.getConstant(Immediate, SelectVT));
6441   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6442 }
6443
6444 /// \brief Return true if \p N implements a horizontal binop and return the
6445 /// operands for the horizontal binop into V0 and V1.
6446 ///
6447 /// This is a helper function of PerformBUILD_VECTORCombine.
6448 /// This function checks that the build_vector \p N in input implements a
6449 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6450 /// operation to match.
6451 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6452 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6453 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6454 /// arithmetic sub.
6455 ///
6456 /// This function only analyzes elements of \p N whose indices are
6457 /// in range [BaseIdx, LastIdx).
6458 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6459                               SelectionDAG &DAG,
6460                               unsigned BaseIdx, unsigned LastIdx,
6461                               SDValue &V0, SDValue &V1) {
6462   EVT VT = N->getValueType(0);
6463
6464   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6465   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6466          "Invalid Vector in input!");
6467
6468   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6469   bool CanFold = true;
6470   unsigned ExpectedVExtractIdx = BaseIdx;
6471   unsigned NumElts = LastIdx - BaseIdx;
6472   V0 = DAG.getUNDEF(VT);
6473   V1 = DAG.getUNDEF(VT);
6474
6475   // Check if N implements a horizontal binop.
6476   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6477     SDValue Op = N->getOperand(i + BaseIdx);
6478
6479     // Skip UNDEFs.
6480     if (Op->getOpcode() == ISD::UNDEF) {
6481       // Update the expected vector extract index.
6482       if (i * 2 == NumElts)
6483         ExpectedVExtractIdx = BaseIdx;
6484       ExpectedVExtractIdx += 2;
6485       continue;
6486     }
6487
6488     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6489
6490     if (!CanFold)
6491       break;
6492
6493     SDValue Op0 = Op.getOperand(0);
6494     SDValue Op1 = Op.getOperand(1);
6495
6496     // Try to match the following pattern:
6497     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6498     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6499         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6500         Op0.getOperand(0) == Op1.getOperand(0) &&
6501         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6502         isa<ConstantSDNode>(Op1.getOperand(1)));
6503     if (!CanFold)
6504       break;
6505
6506     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6507     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6508
6509     if (i * 2 < NumElts) {
6510       if (V0.getOpcode() == ISD::UNDEF)
6511         V0 = Op0.getOperand(0);
6512     } else {
6513       if (V1.getOpcode() == ISD::UNDEF)
6514         V1 = Op0.getOperand(0);
6515       if (i * 2 == NumElts)
6516         ExpectedVExtractIdx = BaseIdx;
6517     }
6518
6519     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6520     if (I0 == ExpectedVExtractIdx)
6521       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6522     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6523       // Try to match the following dag sequence:
6524       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6525       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6526     } else
6527       CanFold = false;
6528
6529     ExpectedVExtractIdx += 2;
6530   }
6531
6532   return CanFold;
6533 }
6534
6535 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6536 /// a concat_vector.
6537 ///
6538 /// This is a helper function of PerformBUILD_VECTORCombine.
6539 /// This function expects two 256-bit vectors called V0 and V1.
6540 /// At first, each vector is split into two separate 128-bit vectors.
6541 /// Then, the resulting 128-bit vectors are used to implement two
6542 /// horizontal binary operations.
6543 ///
6544 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6545 ///
6546 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6547 /// the two new horizontal binop.
6548 /// When Mode is set, the first horizontal binop dag node would take as input
6549 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6550 /// horizontal binop dag node would take as input the lower 128-bit of V1
6551 /// and the upper 128-bit of V1.
6552 ///   Example:
6553 ///     HADD V0_LO, V0_HI
6554 ///     HADD V1_LO, V1_HI
6555 ///
6556 /// Otherwise, the first horizontal binop dag node takes as input the lower
6557 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6558 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6559 ///   Example:
6560 ///     HADD V0_LO, V1_LO
6561 ///     HADD V0_HI, V1_HI
6562 ///
6563 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6564 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6565 /// the upper 128-bits of the result.
6566 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6567                                      SDLoc DL, SelectionDAG &DAG,
6568                                      unsigned X86Opcode, bool Mode,
6569                                      bool isUndefLO, bool isUndefHI) {
6570   EVT VT = V0.getValueType();
6571   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6572          "Invalid nodes in input!");
6573
6574   unsigned NumElts = VT.getVectorNumElements();
6575   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6576   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6577   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6578   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6579   EVT NewVT = V0_LO.getValueType();
6580
6581   SDValue LO = DAG.getUNDEF(NewVT);
6582   SDValue HI = DAG.getUNDEF(NewVT);
6583
6584   if (Mode) {
6585     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6586     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6587       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6588     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6589       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6590   } else {
6591     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6592     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6593                        V1_LO->getOpcode() != ISD::UNDEF))
6594       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6595
6596     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6597                        V1_HI->getOpcode() != ISD::UNDEF))
6598       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6599   }
6600
6601   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6602 }
6603
6604 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6605 /// sequence of 'vadd + vsub + blendi'.
6606 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6607                            const X86Subtarget *Subtarget) {
6608   SDLoc DL(BV);
6609   EVT VT = BV->getValueType(0);
6610   unsigned NumElts = VT.getVectorNumElements();
6611   SDValue InVec0 = DAG.getUNDEF(VT);
6612   SDValue InVec1 = DAG.getUNDEF(VT);
6613
6614   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6615           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6616
6617   // Odd-numbered elements in the input build vector are obtained from
6618   // adding two integer/float elements.
6619   // Even-numbered elements in the input build vector are obtained from
6620   // subtracting two integer/float elements.
6621   unsigned ExpectedOpcode = ISD::FSUB;
6622   unsigned NextExpectedOpcode = ISD::FADD;
6623   bool AddFound = false;
6624   bool SubFound = false;
6625
6626   for (unsigned i = 0, e = NumElts; i != e; i++) {
6627     SDValue Op = BV->getOperand(i);
6628
6629     // Skip 'undef' values.
6630     unsigned Opcode = Op.getOpcode();
6631     if (Opcode == ISD::UNDEF) {
6632       std::swap(ExpectedOpcode, NextExpectedOpcode);
6633       continue;
6634     }
6635
6636     // Early exit if we found an unexpected opcode.
6637     if (Opcode != ExpectedOpcode)
6638       return SDValue();
6639
6640     SDValue Op0 = Op.getOperand(0);
6641     SDValue Op1 = Op.getOperand(1);
6642
6643     // Try to match the following pattern:
6644     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6645     // Early exit if we cannot match that sequence.
6646     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6647         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6648         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6649         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6650         Op0.getOperand(1) != Op1.getOperand(1))
6651       return SDValue();
6652
6653     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6654     if (I0 != i)
6655       return SDValue();
6656
6657     // We found a valid add/sub node. Update the information accordingly.
6658     if (i & 1)
6659       AddFound = true;
6660     else
6661       SubFound = true;
6662
6663     // Update InVec0 and InVec1.
6664     if (InVec0.getOpcode() == ISD::UNDEF)
6665       InVec0 = Op0.getOperand(0);
6666     if (InVec1.getOpcode() == ISD::UNDEF)
6667       InVec1 = Op1.getOperand(0);
6668
6669     // Make sure that operands in input to each add/sub node always
6670     // come from a same pair of vectors.
6671     if (InVec0 != Op0.getOperand(0)) {
6672       if (ExpectedOpcode == ISD::FSUB)
6673         return SDValue();
6674
6675       // FADD is commutable. Try to commute the operands
6676       // and then test again.
6677       std::swap(Op0, Op1);
6678       if (InVec0 != Op0.getOperand(0))
6679         return SDValue();
6680     }
6681
6682     if (InVec1 != Op1.getOperand(0))
6683       return SDValue();
6684
6685     // Update the pair of expected opcodes.
6686     std::swap(ExpectedOpcode, NextExpectedOpcode);
6687   }
6688
6689   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6690   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6691       InVec1.getOpcode() != ISD::UNDEF)
6692     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6693
6694   return SDValue();
6695 }
6696
6697 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6698                                           const X86Subtarget *Subtarget) {
6699   SDLoc DL(N);
6700   EVT VT = N->getValueType(0);
6701   unsigned NumElts = VT.getVectorNumElements();
6702   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6703   SDValue InVec0, InVec1;
6704
6705   // Try to match an ADDSUB.
6706   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6707       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6708     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6709     if (Value.getNode())
6710       return Value;
6711   }
6712
6713   // Try to match horizontal ADD/SUB.
6714   unsigned NumUndefsLO = 0;
6715   unsigned NumUndefsHI = 0;
6716   unsigned Half = NumElts/2;
6717
6718   // Count the number of UNDEF operands in the build_vector in input.
6719   for (unsigned i = 0, e = Half; i != e; ++i)
6720     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6721       NumUndefsLO++;
6722
6723   for (unsigned i = Half, e = NumElts; i != e; ++i)
6724     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6725       NumUndefsHI++;
6726
6727   // Early exit if this is either a build_vector of all UNDEFs or all the
6728   // operands but one are UNDEF.
6729   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6730     return SDValue();
6731
6732   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6733     // Try to match an SSE3 float HADD/HSUB.
6734     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6735       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6736
6737     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6738       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6739   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6740     // Try to match an SSSE3 integer HADD/HSUB.
6741     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6742       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6743
6744     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6745       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6746   }
6747
6748   if (!Subtarget->hasAVX())
6749     return SDValue();
6750
6751   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6752     // Try to match an AVX horizontal add/sub of packed single/double
6753     // precision floating point values from 256-bit vectors.
6754     SDValue InVec2, InVec3;
6755     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6756         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6757         ((InVec0.getOpcode() == ISD::UNDEF ||
6758           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6759         ((InVec1.getOpcode() == ISD::UNDEF ||
6760           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6761       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6762
6763     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6764         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6765         ((InVec0.getOpcode() == ISD::UNDEF ||
6766           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6767         ((InVec1.getOpcode() == ISD::UNDEF ||
6768           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6769       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6770   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6771     // Try to match an AVX2 horizontal add/sub of signed integers.
6772     SDValue InVec2, InVec3;
6773     unsigned X86Opcode;
6774     bool CanFold = true;
6775
6776     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6777         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6778         ((InVec0.getOpcode() == ISD::UNDEF ||
6779           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6780         ((InVec1.getOpcode() == ISD::UNDEF ||
6781           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6782       X86Opcode = X86ISD::HADD;
6783     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6784         isHorizontalBinOp(BV, ISD::SUB, 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       X86Opcode = X86ISD::HSUB;
6790     else
6791       CanFold = false;
6792
6793     if (CanFold) {
6794       // Fold this build_vector into a single horizontal add/sub.
6795       // Do this only if the target has AVX2.
6796       if (Subtarget->hasAVX2())
6797         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6798
6799       // Do not try to expand this build_vector into a pair of horizontal
6800       // add/sub if we can emit a pair of scalar add/sub.
6801       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6802         return SDValue();
6803
6804       // Convert this build_vector into a pair of horizontal binop followed by
6805       // a concat vector.
6806       bool isUndefLO = NumUndefsLO == Half;
6807       bool isUndefHI = NumUndefsHI == Half;
6808       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6809                                    isUndefLO, isUndefHI);
6810     }
6811   }
6812
6813   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6814        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6815     unsigned X86Opcode;
6816     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6817       X86Opcode = X86ISD::HADD;
6818     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6819       X86Opcode = X86ISD::HSUB;
6820     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6821       X86Opcode = X86ISD::FHADD;
6822     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6823       X86Opcode = X86ISD::FHSUB;
6824     else
6825       return SDValue();
6826
6827     // Don't try to expand this build_vector into a pair of horizontal add/sub
6828     // if we can simply 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 two horizontal add/sub followed by
6833     // a concat vector.
6834     bool isUndefLO = NumUndefsLO == Half;
6835     bool isUndefHI = NumUndefsHI == Half;
6836     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6837                                  isUndefLO, isUndefHI);
6838   }
6839
6840   return SDValue();
6841 }
6842
6843 SDValue
6844 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6845   SDLoc dl(Op);
6846
6847   MVT VT = Op.getSimpleValueType();
6848   MVT ExtVT = VT.getVectorElementType();
6849   unsigned NumElems = Op.getNumOperands();
6850
6851   // Generate vectors for predicate vectors.
6852   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6853     return LowerBUILD_VECTORvXi1(Op, DAG);
6854
6855   // Vectors containing all zeros can be matched by pxor and xorps later
6856   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6857     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6858     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6859     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6860       return Op;
6861
6862     return getZeroVector(VT, Subtarget, DAG, dl);
6863   }
6864
6865   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6866   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6867   // vpcmpeqd on 256-bit vectors.
6868   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6869     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6870       return Op;
6871
6872     if (!VT.is512BitVector())
6873       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6874   }
6875
6876   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6877   if (Broadcast.getNode())
6878     return Broadcast;
6879
6880   unsigned EVTBits = ExtVT.getSizeInBits();
6881
6882   unsigned NumZero  = 0;
6883   unsigned NumNonZero = 0;
6884   unsigned NonZeros = 0;
6885   bool IsAllConstants = true;
6886   SmallSet<SDValue, 8> Values;
6887   for (unsigned i = 0; i < NumElems; ++i) {
6888     SDValue Elt = Op.getOperand(i);
6889     if (Elt.getOpcode() == ISD::UNDEF)
6890       continue;
6891     Values.insert(Elt);
6892     if (Elt.getOpcode() != ISD::Constant &&
6893         Elt.getOpcode() != ISD::ConstantFP)
6894       IsAllConstants = false;
6895     if (X86::isZeroNode(Elt))
6896       NumZero++;
6897     else {
6898       NonZeros |= (1 << i);
6899       NumNonZero++;
6900     }
6901   }
6902
6903   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6904   if (NumNonZero == 0)
6905     return DAG.getUNDEF(VT);
6906
6907   // Special case for single non-zero, non-undef, element.
6908   if (NumNonZero == 1) {
6909     unsigned Idx = countTrailingZeros(NonZeros);
6910     SDValue Item = Op.getOperand(Idx);
6911
6912     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6913     // the value are obviously zero, truncate the value to i32 and do the
6914     // insertion that way.  Only do this if the value is non-constant or if the
6915     // value is a constant being inserted into element 0.  It is cheaper to do
6916     // a constant pool load than it is to do a movd + shuffle.
6917     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6918         (!IsAllConstants || Idx == 0)) {
6919       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6920         // Handle SSE only.
6921         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6922         EVT VecVT = MVT::v4i32;
6923         unsigned VecElts = 4;
6924
6925         // Truncate the value (which may itself be a constant) to i32, and
6926         // convert it to a vector with movd (S2V+shuffle to zero extend).
6927         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6928         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6929
6930         // If using the new shuffle lowering, just directly insert this.
6931         if (ExperimentalVectorShuffleLowering)
6932           return DAG.getNode(
6933               ISD::BITCAST, dl, VT,
6934               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6935
6936         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6937
6938         // Now we have our 32-bit value zero extended in the low element of
6939         // a vector.  If Idx != 0, swizzle it into place.
6940         if (Idx != 0) {
6941           SmallVector<int, 4> Mask;
6942           Mask.push_back(Idx);
6943           for (unsigned i = 1; i != VecElts; ++i)
6944             Mask.push_back(i);
6945           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6946                                       &Mask[0]);
6947         }
6948         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6949       }
6950     }
6951
6952     // If we have a constant or non-constant insertion into the low element of
6953     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6954     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6955     // depending on what the source datatype is.
6956     if (Idx == 0) {
6957       if (NumZero == 0)
6958         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6959
6960       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6961           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6962         if (VT.is256BitVector() || VT.is512BitVector()) {
6963           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6964           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6965                              Item, DAG.getIntPtrConstant(0));
6966         }
6967         assert(VT.is128BitVector() && "Expected an SSE value type!");
6968         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6969         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6970         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6971       }
6972
6973       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6974         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6975         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6976         if (VT.is256BitVector()) {
6977           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6978           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6979         } else {
6980           assert(VT.is128BitVector() && "Expected an SSE value type!");
6981           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6982         }
6983         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6984       }
6985     }
6986
6987     // Is it a vector logical left shift?
6988     if (NumElems == 2 && Idx == 1 &&
6989         X86::isZeroNode(Op.getOperand(0)) &&
6990         !X86::isZeroNode(Op.getOperand(1))) {
6991       unsigned NumBits = VT.getSizeInBits();
6992       return getVShift(true, VT,
6993                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6994                                    VT, Op.getOperand(1)),
6995                        NumBits/2, DAG, *this, dl);
6996     }
6997
6998     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6999       return SDValue();
7000
7001     // Otherwise, if this is a vector with i32 or f32 elements, and the element
7002     // is a non-constant being inserted into an element other than the low one,
7003     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
7004     // movd/movss) to move this into the low element, then shuffle it into
7005     // place.
7006     if (EVTBits == 32) {
7007       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
7008
7009       // If using the new shuffle lowering, just directly insert this.
7010       if (ExperimentalVectorShuffleLowering)
7011         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
7012
7013       // Turn it into a shuffle of zero and zero-extended scalar to vector.
7014       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
7015       SmallVector<int, 8> MaskVec;
7016       for (unsigned i = 0; i != NumElems; ++i)
7017         MaskVec.push_back(i == Idx ? 0 : 1);
7018       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
7019     }
7020   }
7021
7022   // Splat is obviously ok. Let legalizer expand it to a shuffle.
7023   if (Values.size() == 1) {
7024     if (EVTBits == 32) {
7025       // Instead of a shuffle like this:
7026       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
7027       // Check if it's possible to issue this instead.
7028       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
7029       unsigned Idx = countTrailingZeros(NonZeros);
7030       SDValue Item = Op.getOperand(Idx);
7031       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
7032         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
7033     }
7034     return SDValue();
7035   }
7036
7037   // A vector full of immediates; various special cases are already
7038   // handled, so this is best done with a single constant-pool load.
7039   if (IsAllConstants)
7040     return SDValue();
7041
7042   // For AVX-length vectors, see if we can use a vector load to get all of the
7043   // elements, otherwise build the individual 128-bit pieces and use
7044   // shuffles to put them in place.
7045   if (VT.is256BitVector() || VT.is512BitVector()) {
7046     SmallVector<SDValue, 64> V;
7047     for (unsigned i = 0; i != NumElems; ++i)
7048       V.push_back(Op.getOperand(i));
7049
7050     // Check for a build vector of consecutive loads.
7051     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
7052       return LD;
7053
7054     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
7055
7056     // Build both the lower and upper subvector.
7057     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7058                                 makeArrayRef(&V[0], NumElems/2));
7059     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7060                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
7061
7062     // Recreate the wider vector with the lower and upper part.
7063     if (VT.is256BitVector())
7064       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7065     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7066   }
7067
7068   // Let legalizer expand 2-wide build_vectors.
7069   if (EVTBits == 64) {
7070     if (NumNonZero == 1) {
7071       // One half is zero or undef.
7072       unsigned Idx = countTrailingZeros(NonZeros);
7073       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
7074                                  Op.getOperand(Idx));
7075       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
7076     }
7077     return SDValue();
7078   }
7079
7080   // If element VT is < 32 bits, convert it to inserts into a zero vector.
7081   if (EVTBits == 8 && NumElems == 16) {
7082     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
7083                                         Subtarget, *this);
7084     if (V.getNode()) return V;
7085   }
7086
7087   if (EVTBits == 16 && NumElems == 8) {
7088     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
7089                                       Subtarget, *this);
7090     if (V.getNode()) return V;
7091   }
7092
7093   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
7094   if (EVTBits == 32 && NumElems == 4) {
7095     SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
7096     if (V.getNode())
7097       return V;
7098   }
7099
7100   // If element VT is == 32 bits, turn it into a number of shuffles.
7101   SmallVector<SDValue, 8> V(NumElems);
7102   if (NumElems == 4 && NumZero > 0) {
7103     for (unsigned i = 0; i < 4; ++i) {
7104       bool isZero = !(NonZeros & (1 << i));
7105       if (isZero)
7106         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7107       else
7108         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7109     }
7110
7111     for (unsigned i = 0; i < 2; ++i) {
7112       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7113         default: break;
7114         case 0:
7115           V[i] = V[i*2];  // Must be a zero vector.
7116           break;
7117         case 1:
7118           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7119           break;
7120         case 2:
7121           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7122           break;
7123         case 3:
7124           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7125           break;
7126       }
7127     }
7128
7129     bool Reverse1 = (NonZeros & 0x3) == 2;
7130     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7131     int MaskVec[] = {
7132       Reverse1 ? 1 : 0,
7133       Reverse1 ? 0 : 1,
7134       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7135       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7136     };
7137     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7138   }
7139
7140   if (Values.size() > 1 && VT.is128BitVector()) {
7141     // Check for a build vector of consecutive loads.
7142     for (unsigned i = 0; i < NumElems; ++i)
7143       V[i] = Op.getOperand(i);
7144
7145     // Check for elements which are consecutive loads.
7146     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7147     if (LD.getNode())
7148       return LD;
7149
7150     // Check for a build vector from mostly shuffle plus few inserting.
7151     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7152     if (Sh.getNode())
7153       return Sh;
7154
7155     // For SSE 4.1, use insertps to put the high elements into the low element.
7156     if (getSubtarget()->hasSSE41()) {
7157       SDValue Result;
7158       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7159         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7160       else
7161         Result = DAG.getUNDEF(VT);
7162
7163       for (unsigned i = 1; i < NumElems; ++i) {
7164         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7165         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7166                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7167       }
7168       return Result;
7169     }
7170
7171     // Otherwise, expand into a number of unpckl*, start by extending each of
7172     // our (non-undef) elements to the full vector width with the element in the
7173     // bottom slot of the vector (which generates no code for SSE).
7174     for (unsigned i = 0; i < NumElems; ++i) {
7175       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7176         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7177       else
7178         V[i] = DAG.getUNDEF(VT);
7179     }
7180
7181     // Next, we iteratively mix elements, e.g. for v4f32:
7182     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7183     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7184     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7185     unsigned EltStride = NumElems >> 1;
7186     while (EltStride != 0) {
7187       for (unsigned i = 0; i < EltStride; ++i) {
7188         // If V[i+EltStride] is undef and this is the first round of mixing,
7189         // then it is safe to just drop this shuffle: V[i] is already in the
7190         // right place, the one element (since it's the first round) being
7191         // inserted as undef can be dropped.  This isn't safe for successive
7192         // rounds because they will permute elements within both vectors.
7193         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7194             EltStride == NumElems/2)
7195           continue;
7196
7197         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7198       }
7199       EltStride >>= 1;
7200     }
7201     return V[0];
7202   }
7203   return SDValue();
7204 }
7205
7206 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7207 // to create 256-bit vectors from two other 128-bit ones.
7208 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7209   SDLoc dl(Op);
7210   MVT ResVT = Op.getSimpleValueType();
7211
7212   assert((ResVT.is256BitVector() ||
7213           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7214
7215   SDValue V1 = Op.getOperand(0);
7216   SDValue V2 = Op.getOperand(1);
7217   unsigned NumElems = ResVT.getVectorNumElements();
7218   if(ResVT.is256BitVector())
7219     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7220
7221   if (Op.getNumOperands() == 4) {
7222     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7223                                 ResVT.getVectorNumElements()/2);
7224     SDValue V3 = Op.getOperand(2);
7225     SDValue V4 = Op.getOperand(3);
7226     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7227       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7228   }
7229   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7230 }
7231
7232 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7233   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7234   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7235          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7236           Op.getNumOperands() == 4)));
7237
7238   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7239   // from two other 128-bit ones.
7240
7241   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7242   return LowerAVXCONCAT_VECTORS(Op, DAG);
7243 }
7244
7245
7246 //===----------------------------------------------------------------------===//
7247 // Vector shuffle lowering
7248 //
7249 // This is an experimental code path for lowering vector shuffles on x86. It is
7250 // designed to handle arbitrary vector shuffles and blends, gracefully
7251 // degrading performance as necessary. It works hard to recognize idiomatic
7252 // shuffles and lower them to optimal instruction patterns without leaving
7253 // a framework that allows reasonably efficient handling of all vector shuffle
7254 // patterns.
7255 //===----------------------------------------------------------------------===//
7256
7257 /// \brief Tiny helper function to identify a no-op mask.
7258 ///
7259 /// This is a somewhat boring predicate function. It checks whether the mask
7260 /// array input, which is assumed to be a single-input shuffle mask of the kind
7261 /// used by the X86 shuffle instructions (not a fully general
7262 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7263 /// in-place shuffle are 'no-op's.
7264 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7265   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7266     if (Mask[i] != -1 && Mask[i] != i)
7267       return false;
7268   return true;
7269 }
7270
7271 /// \brief Helper function to classify a mask as a single-input mask.
7272 ///
7273 /// This isn't a generic single-input test because in the vector shuffle
7274 /// lowering we canonicalize single inputs to be the first input operand. This
7275 /// means we can more quickly test for a single input by only checking whether
7276 /// an input from the second operand exists. We also assume that the size of
7277 /// mask corresponds to the size of the input vectors which isn't true in the
7278 /// fully general case.
7279 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7280   for (int M : Mask)
7281     if (M >= (int)Mask.size())
7282       return false;
7283   return true;
7284 }
7285
7286 /// \brief Test whether there are elements crossing 128-bit lanes in this
7287 /// shuffle mask.
7288 ///
7289 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
7290 /// and we routinely test for these.
7291 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
7292   int LaneSize = 128 / VT.getScalarSizeInBits();
7293   int Size = Mask.size();
7294   for (int i = 0; i < Size; ++i)
7295     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
7296       return true;
7297   return false;
7298 }
7299
7300 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
7301 ///
7302 /// This checks a shuffle mask to see if it is performing the same
7303 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
7304 /// that it is also not lane-crossing. It may however involve a blend from the
7305 /// same lane of a second vector.
7306 ///
7307 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
7308 /// non-trivial to compute in the face of undef lanes. The representation is
7309 /// *not* suitable for use with existing 128-bit shuffles as it will contain
7310 /// entries from both V1 and V2 inputs to the wider mask.
7311 static bool
7312 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7313                                 SmallVectorImpl<int> &RepeatedMask) {
7314   int LaneSize = 128 / VT.getScalarSizeInBits();
7315   RepeatedMask.resize(LaneSize, -1);
7316   int Size = Mask.size();
7317   for (int i = 0; i < Size; ++i) {
7318     if (Mask[i] < 0)
7319       continue;
7320     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
7321       // This entry crosses lanes, so there is no way to model this shuffle.
7322       return false;
7323
7324     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
7325     if (RepeatedMask[i % LaneSize] == -1)
7326       // This is the first non-undef entry in this slot of a 128-bit lane.
7327       RepeatedMask[i % LaneSize] =
7328           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
7329     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
7330       // Found a mismatch with the repeated mask.
7331       return false;
7332   }
7333   return true;
7334 }
7335
7336 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7337 // 2013 will allow us to use it as a non-type template parameter.
7338 namespace {
7339
7340 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7341 ///
7342 /// See its documentation for details.
7343 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7344   if (Mask.size() != Args.size())
7345     return false;
7346   for (int i = 0, e = Mask.size(); i < e; ++i) {
7347     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7348     if (Mask[i] != -1 && Mask[i] != *Args[i])
7349       return false;
7350   }
7351   return true;
7352 }
7353
7354 } // namespace
7355
7356 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7357 /// arguments.
7358 ///
7359 /// This is a fast way to test a shuffle mask against a fixed pattern:
7360 ///
7361 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7362 ///
7363 /// It returns true if the mask is exactly as wide as the argument list, and
7364 /// each element of the mask is either -1 (signifying undef) or the value given
7365 /// in the argument.
7366 static const VariadicFunction1<
7367     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7368
7369 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7370 ///
7371 /// This helper function produces an 8-bit shuffle immediate corresponding to
7372 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7373 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7374 /// example.
7375 ///
7376 /// NB: We rely heavily on "undef" masks preserving the input lane.
7377 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7378                                           SelectionDAG &DAG) {
7379   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7380   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7381   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7382   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7383   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7384
7385   unsigned Imm = 0;
7386   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7387   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7388   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7389   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7390   return DAG.getConstant(Imm, MVT::i8);
7391 }
7392
7393 /// \brief Try to emit a blend instruction for a shuffle.
7394 ///
7395 /// This doesn't do any checks for the availability of instructions for blending
7396 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7397 /// be matched in the backend with the type given. What it does check for is
7398 /// that the shuffle mask is in fact a blend.
7399 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7400                                          SDValue V2, ArrayRef<int> Mask,
7401                                          const X86Subtarget *Subtarget,
7402                                          SelectionDAG &DAG) {
7403
7404   unsigned BlendMask = 0;
7405   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7406     if (Mask[i] >= Size) {
7407       if (Mask[i] != i + Size)
7408         return SDValue(); // Shuffled V2 input!
7409       BlendMask |= 1u << i;
7410       continue;
7411     }
7412     if (Mask[i] >= 0 && Mask[i] != i)
7413       return SDValue(); // Shuffled V1 input!
7414   }
7415   switch (VT.SimpleTy) {
7416   case MVT::v2f64:
7417   case MVT::v4f32:
7418   case MVT::v4f64:
7419   case MVT::v8f32:
7420     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7421                        DAG.getConstant(BlendMask, MVT::i8));
7422
7423   case MVT::v4i64:
7424   case MVT::v8i32:
7425     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7426     // FALLTHROUGH
7427   case MVT::v2i64:
7428   case MVT::v4i32:
7429     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7430     // that instruction.
7431     if (Subtarget->hasAVX2()) {
7432       // Scale the blend by the number of 32-bit dwords per element.
7433       int Scale =  VT.getScalarSizeInBits() / 32;
7434       BlendMask = 0;
7435       for (int i = 0, Size = Mask.size(); i < Size; ++i)
7436         if (Mask[i] >= Size)
7437           for (int j = 0; j < Scale; ++j)
7438             BlendMask |= 1u << (i * Scale + j);
7439
7440       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7441       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
7442       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
7443       return DAG.getNode(ISD::BITCAST, DL, VT,
7444                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7445                                      DAG.getConstant(BlendMask, MVT::i8)));
7446     }
7447     // FALLTHROUGH
7448   case MVT::v8i16: {
7449     // For integer shuffles we need to expand the mask and cast the inputs to
7450     // v8i16s prior to blending.
7451     int Scale = 8 / VT.getVectorNumElements();
7452     BlendMask = 0;
7453     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7454       if (Mask[i] >= Size)
7455         for (int j = 0; j < Scale; ++j)
7456           BlendMask |= 1u << (i * Scale + j);
7457
7458     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7459     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7460     return DAG.getNode(ISD::BITCAST, DL, VT,
7461                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7462                                    DAG.getConstant(BlendMask, MVT::i8)));
7463   }
7464
7465   case MVT::v16i16: {
7466     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7467     SmallVector<int, 8> RepeatedMask;
7468     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7469       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7470       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7471       BlendMask = 0;
7472       for (int i = 0; i < 8; ++i)
7473         if (RepeatedMask[i] >= 16)
7474           BlendMask |= 1u << i;
7475       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7476                          DAG.getConstant(BlendMask, MVT::i8));
7477     }
7478   }
7479     // FALLTHROUGH
7480   case MVT::v32i8: {
7481     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7482     // Scale the blend by the number of bytes per element.
7483     int Scale =  VT.getScalarSizeInBits() / 8;
7484     assert(Mask.size() * Scale == 32 && "Not a 256-bit vector!");
7485
7486     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7487     // mix of LLVM's code generator and the x86 backend. We tell the code
7488     // generator that boolean values in the elements of an x86 vector register
7489     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7490     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7491     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7492     // of the element (the remaining are ignored) and 0 in that high bit would
7493     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7494     // the LLVM model for boolean values in vector elements gets the relevant
7495     // bit set, it is set backwards and over constrained relative to x86's
7496     // actual model.
7497     SDValue VSELECTMask[32];
7498     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7499       for (int j = 0; j < Scale; ++j)
7500         VSELECTMask[Scale * i + j] =
7501             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7502                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8);
7503
7504     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1);
7505     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V2);
7506     return DAG.getNode(
7507         ISD::BITCAST, DL, VT,
7508         DAG.getNode(ISD::VSELECT, DL, MVT::v32i8,
7509                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, VSELECTMask),
7510                     V1, V2));
7511   }
7512
7513   default:
7514     llvm_unreachable("Not a supported integer vector type!");
7515   }
7516 }
7517
7518 /// \brief Generic routine to lower a shuffle and blend as a decomposed set of
7519 /// unblended shuffles followed by an unshuffled blend.
7520 ///
7521 /// This matches the extremely common pattern for handling combined
7522 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7523 /// operations.
7524 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7525                                                           SDValue V1,
7526                                                           SDValue V2,
7527                                                           ArrayRef<int> Mask,
7528                                                           SelectionDAG &DAG) {
7529   // Shuffle the input elements into the desired positions in V1 and V2 and
7530   // blend them together.
7531   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7532   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7533   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7534   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7535     if (Mask[i] >= 0 && Mask[i] < Size) {
7536       V1Mask[i] = Mask[i];
7537       BlendMask[i] = i;
7538     } else if (Mask[i] >= Size) {
7539       V2Mask[i] = Mask[i] - Size;
7540       BlendMask[i] = i + Size;
7541     }
7542
7543   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7544   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7545   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7546 }
7547
7548 /// \brief Try to lower a vector shuffle as a byte rotation.
7549 ///
7550 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7551 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7552 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7553 /// try to generically lower a vector shuffle through such an pattern. It
7554 /// does not check for the profitability of lowering either as PALIGNR or
7555 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7556 /// This matches shuffle vectors that look like:
7557 ///
7558 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7559 ///
7560 /// Essentially it concatenates V1 and V2, shifts right by some number of
7561 /// elements, and takes the low elements as the result. Note that while this is
7562 /// specified as a *right shift* because x86 is little-endian, it is a *left
7563 /// rotate* of the vector lanes.
7564 ///
7565 /// Note that this only handles 128-bit vector widths currently.
7566 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7567                                               SDValue V2,
7568                                               ArrayRef<int> Mask,
7569                                               const X86Subtarget *Subtarget,
7570                                               SelectionDAG &DAG) {
7571   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7572
7573   // We need to detect various ways of spelling a rotation:
7574   //   [11, 12, 13, 14, 15,  0,  1,  2]
7575   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7576   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7577   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7578   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7579   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7580   int Rotation = 0;
7581   SDValue Lo, Hi;
7582   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7583     if (Mask[i] == -1)
7584       continue;
7585     assert(Mask[i] >= 0 && "Only -1 is a valid negative mask element!");
7586
7587     // Based on the mod-Size value of this mask element determine where
7588     // a rotated vector would have started.
7589     int StartIdx = i - (Mask[i] % Size);
7590     if (StartIdx == 0)
7591       // The identity rotation isn't interesting, stop.
7592       return SDValue();
7593
7594     // If we found the tail of a vector the rotation must be the missing
7595     // front. If we found the head of a vector, it must be how much of the head.
7596     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
7597
7598     if (Rotation == 0)
7599       Rotation = CandidateRotation;
7600     else if (Rotation != CandidateRotation)
7601       // The rotations don't match, so we can't match this mask.
7602       return SDValue();
7603
7604     // Compute which value this mask is pointing at.
7605     SDValue MaskV = Mask[i] < Size ? V1 : V2;
7606
7607     // Compute which of the two target values this index should be assigned to.
7608     // This reflects whether the high elements are remaining or the low elements
7609     // are remaining.
7610     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7611
7612     // Either set up this value if we've not encountered it before, or check
7613     // that it remains consistent.
7614     if (!TargetV)
7615       TargetV = MaskV;
7616     else if (TargetV != MaskV)
7617       // This may be a rotation, but it pulls from the inputs in some
7618       // unsupported interleaving.
7619       return SDValue();
7620   }
7621
7622   // Check that we successfully analyzed the mask, and normalize the results.
7623   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7624   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7625   if (!Lo)
7626     Lo = Hi;
7627   else if (!Hi)
7628     Hi = Lo;
7629
7630   assert(VT.getSizeInBits() == 128 &&
7631          "Rotate-based lowering only supports 128-bit lowering!");
7632   assert(Mask.size() <= 16 &&
7633          "Can shuffle at most 16 bytes in a 128-bit vector!");
7634
7635   // The actual rotate instruction rotates bytes, so we need to scale the
7636   // rotation based on how many bytes are in the vector.
7637   int Scale = 16 / Mask.size();
7638
7639   // SSSE3 targets can use the palignr instruction
7640   if (Subtarget->hasSSSE3()) {
7641     // Cast the inputs to v16i8 to match PALIGNR.
7642     Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Lo);
7643     Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Hi);
7644
7645     return DAG.getNode(ISD::BITCAST, DL, VT,
7646                        DAG.getNode(X86ISD::PALIGNR, DL, MVT::v16i8, Hi, Lo,
7647                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
7648   }
7649
7650   // Default SSE2 implementation
7651   int LoByteShift = 16 - Rotation * Scale;
7652   int HiByteShift = Rotation * Scale;
7653
7654   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7655   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
7656   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
7657
7658   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7659                                 DAG.getConstant(8 * LoByteShift, MVT::i8));
7660   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7661                                 DAG.getConstant(8 * HiByteShift, MVT::i8));
7662   return DAG.getNode(ISD::BITCAST, DL, VT,
7663                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7664 }
7665
7666 /// \brief Compute whether each element of a shuffle is zeroable.
7667 ///
7668 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7669 /// Either it is an undef element in the shuffle mask, the element of the input
7670 /// referenced is undef, or the element of the input referenced is known to be
7671 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7672 /// as many lanes with this technique as possible to simplify the remaining
7673 /// shuffle.
7674 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7675                                                      SDValue V1, SDValue V2) {
7676   SmallBitVector Zeroable(Mask.size(), false);
7677
7678   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7679   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7680
7681   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7682     int M = Mask[i];
7683     // Handle the easy cases.
7684     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7685       Zeroable[i] = true;
7686       continue;
7687     }
7688
7689     // If this is an index into a build_vector node, dig out the input value and
7690     // use it.
7691     SDValue V = M < Size ? V1 : V2;
7692     if (V.getOpcode() != ISD::BUILD_VECTOR)
7693       continue;
7694
7695     SDValue Input = V.getOperand(M % Size);
7696     // The UNDEF opcode check really should be dead code here, but not quite
7697     // worth asserting on (it isn't invalid, just unexpected).
7698     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
7699       Zeroable[i] = true;
7700   }
7701
7702   return Zeroable;
7703 }
7704
7705 /// \brief Try to lower a vector shuffle as a byte shift (shifts in zeros).
7706 ///
7707 /// Attempts to match a shuffle mask against the PSRLDQ and PSLLDQ SSE2
7708 /// byte-shift instructions. The mask must consist of a shifted sequential
7709 /// shuffle from one of the input vectors and zeroable elements for the
7710 /// remaining 'shifted in' elements.
7711 ///
7712 /// Note that this only handles 128-bit vector widths currently.
7713 static SDValue lowerVectorShuffleAsByteShift(SDLoc DL, MVT VT, SDValue V1,
7714                                              SDValue V2, ArrayRef<int> Mask,
7715                                              SelectionDAG &DAG) {
7716   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7717
7718   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7719
7720   int Size = Mask.size();
7721   int Scale = 16 / Size;
7722
7723   for (int Shift = 1; Shift < Size; Shift++) {
7724     int ByteShift = Shift * Scale;
7725
7726     // PSRLDQ : (little-endian) right byte shift
7727     // [ 5,  6,  7, zz, zz, zz, zz, zz]
7728     // [ -1, 5,  6,  7, zz, zz, zz, zz]
7729     // [  1, 2, -1, -1, -1, -1, zz, zz]
7730     bool ZeroableRight = true;
7731     for (int i = Size - Shift; i < Size; i++) {
7732       ZeroableRight &= Zeroable[i];
7733     }
7734
7735     if (ZeroableRight) {
7736       bool ValidShiftRight1 =
7737           isSequentialOrUndefInRange(Mask, 0, Size - Shift, Shift);
7738       bool ValidShiftRight2 =
7739           isSequentialOrUndefInRange(Mask, 0, Size - Shift, Size + Shift);
7740
7741       if (ValidShiftRight1 || ValidShiftRight2) {
7742         // Cast the inputs to v2i64 to match PSRLDQ.
7743         SDValue &TargetV = ValidShiftRight1 ? V1 : V2;
7744         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7745         SDValue Shifted = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, V,
7746                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7747         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7748       }
7749     }
7750
7751     // PSLLDQ : (little-endian) left byte shift
7752     // [ zz,  0,  1,  2,  3,  4,  5,  6]
7753     // [ zz, zz, -1, -1,  2,  3,  4, -1]
7754     // [ zz, zz, zz, zz, zz, zz, -1,  1]
7755     bool ZeroableLeft = true;
7756     for (int i = 0; i < Shift; i++) {
7757       ZeroableLeft &= Zeroable[i];
7758     }
7759
7760     if (ZeroableLeft) {
7761       bool ValidShiftLeft1 =
7762           isSequentialOrUndefInRange(Mask, Shift, Size - Shift, 0);
7763       bool ValidShiftLeft2 =
7764           isSequentialOrUndefInRange(Mask, Shift, Size - Shift, Size);
7765
7766       if (ValidShiftLeft1 || ValidShiftLeft2) {
7767         // Cast the inputs to v2i64 to match PSLLDQ.
7768         SDValue &TargetV = ValidShiftLeft1 ? V1 : V2;
7769         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7770         SDValue Shifted = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, V,
7771                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7772         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7773       }
7774     }
7775   }
7776
7777   return SDValue();
7778 }
7779
7780 /// \brief Lower a vector shuffle as a zero or any extension.
7781 ///
7782 /// Given a specific number of elements, element bit width, and extension
7783 /// stride, produce either a zero or any extension based on the available
7784 /// features of the subtarget.
7785 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7786     SDLoc DL, MVT VT, int NumElements, int Scale, bool AnyExt, SDValue InputV,
7787     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7788   assert(Scale > 1 && "Need a scale to extend.");
7789   int EltBits = VT.getSizeInBits() / NumElements;
7790   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7791          "Only 8, 16, and 32 bit elements can be extended.");
7792   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7793
7794   // Found a valid zext mask! Try various lowering strategies based on the
7795   // input type and available ISA extensions.
7796   if (Subtarget->hasSSE41()) {
7797     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7798     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7799                                  NumElements / Scale);
7800     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7801     return DAG.getNode(ISD::BITCAST, DL, VT,
7802                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7803   }
7804
7805   // For any extends we can cheat for larger element sizes and use shuffle
7806   // instructions that can fold with a load and/or copy.
7807   if (AnyExt && EltBits == 32) {
7808     int PSHUFDMask[4] = {0, -1, 1, -1};
7809     return DAG.getNode(
7810         ISD::BITCAST, DL, VT,
7811         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7812                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7813                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7814   }
7815   if (AnyExt && EltBits == 16 && Scale > 2) {
7816     int PSHUFDMask[4] = {0, -1, 0, -1};
7817     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7818                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7819                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
7820     int PSHUFHWMask[4] = {1, -1, -1, -1};
7821     return DAG.getNode(
7822         ISD::BITCAST, DL, VT,
7823         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7824                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
7825                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
7826   }
7827
7828   // If this would require more than 2 unpack instructions to expand, use
7829   // pshufb when available. We can only use more than 2 unpack instructions
7830   // when zero extending i8 elements which also makes it easier to use pshufb.
7831   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7832     assert(NumElements == 16 && "Unexpected byte vector width!");
7833     SDValue PSHUFBMask[16];
7834     for (int i = 0; i < 16; ++i)
7835       PSHUFBMask[i] =
7836           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
7837     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
7838     return DAG.getNode(ISD::BITCAST, DL, VT,
7839                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7840                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
7841                                                MVT::v16i8, PSHUFBMask)));
7842   }
7843
7844   // Otherwise emit a sequence of unpacks.
7845   do {
7846     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7847     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7848                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7849     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7850     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7851     Scale /= 2;
7852     EltBits *= 2;
7853     NumElements /= 2;
7854   } while (Scale > 1);
7855   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
7856 }
7857
7858 /// \brief Try to lower a vector shuffle as a zero extension on any micrarch.
7859 ///
7860 /// This routine will try to do everything in its power to cleverly lower
7861 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7862 /// check for the profitability of this lowering,  it tries to aggressively
7863 /// match this pattern. It will use all of the micro-architectural details it
7864 /// can to emit an efficient lowering. It handles both blends with all-zero
7865 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7866 /// masking out later).
7867 ///
7868 /// The reason we have dedicated lowering for zext-style shuffles is that they
7869 /// are both incredibly common and often quite performance sensitive.
7870 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7871     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7872     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7873   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7874
7875   int Bits = VT.getSizeInBits();
7876   int NumElements = Mask.size();
7877
7878   // Define a helper function to check a particular ext-scale and lower to it if
7879   // valid.
7880   auto Lower = [&](int Scale) -> SDValue {
7881     SDValue InputV;
7882     bool AnyExt = true;
7883     for (int i = 0; i < NumElements; ++i) {
7884       if (Mask[i] == -1)
7885         continue; // Valid anywhere but doesn't tell us anything.
7886       if (i % Scale != 0) {
7887         // Each of the extend elements needs to be zeroable.
7888         if (!Zeroable[i])
7889           return SDValue();
7890
7891         // We no lorger are in the anyext case.
7892         AnyExt = false;
7893         continue;
7894       }
7895
7896       // Each of the base elements needs to be consecutive indices into the
7897       // same input vector.
7898       SDValue V = Mask[i] < NumElements ? V1 : V2;
7899       if (!InputV)
7900         InputV = V;
7901       else if (InputV != V)
7902         return SDValue(); // Flip-flopping inputs.
7903
7904       if (Mask[i] % NumElements != i / Scale)
7905         return SDValue(); // Non-consecutive strided elemenst.
7906     }
7907
7908     // If we fail to find an input, we have a zero-shuffle which should always
7909     // have already been handled.
7910     // FIXME: Maybe handle this here in case during blending we end up with one?
7911     if (!InputV)
7912       return SDValue();
7913
7914     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7915         DL, VT, NumElements, Scale, AnyExt, InputV, Subtarget, DAG);
7916   };
7917
7918   // The widest scale possible for extending is to a 64-bit integer.
7919   assert(Bits % 64 == 0 &&
7920          "The number of bits in a vector must be divisible by 64 on x86!");
7921   int NumExtElements = Bits / 64;
7922
7923   // Each iteration, try extending the elements half as much, but into twice as
7924   // many elements.
7925   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7926     assert(NumElements % NumExtElements == 0 &&
7927            "The input vector size must be divisble by the extended size.");
7928     if (SDValue V = Lower(NumElements / NumExtElements))
7929       return V;
7930   }
7931
7932   // No viable ext lowering found.
7933   return SDValue();
7934 }
7935
7936 /// \brief Try to get a scalar value for a specific element of a vector.
7937 ///
7938 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7939 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7940                                               SelectionDAG &DAG) {
7941   MVT VT = V.getSimpleValueType();
7942   MVT EltVT = VT.getVectorElementType();
7943   while (V.getOpcode() == ISD::BITCAST)
7944     V = V.getOperand(0);
7945   // If the bitcasts shift the element size, we can't extract an equivalent
7946   // element from it.
7947   MVT NewVT = V.getSimpleValueType();
7948   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7949     return SDValue();
7950
7951   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7952       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
7953     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
7954
7955   return SDValue();
7956 }
7957
7958 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7959 ///
7960 /// This is particularly important because the set of instructions varies
7961 /// significantly based on whether the operand is a load or not.
7962 static bool isShuffleFoldableLoad(SDValue V) {
7963   while (V.getOpcode() == ISD::BITCAST)
7964     V = V.getOperand(0);
7965
7966   return ISD::isNON_EXTLoad(V.getNode());
7967 }
7968
7969 /// \brief Try to lower insertion of a single element into a zero vector.
7970 ///
7971 /// This is a common pattern that we have especially efficient patterns to lower
7972 /// across all subtarget feature sets.
7973 static SDValue lowerVectorShuffleAsElementInsertion(
7974     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7975     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7976   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7977   MVT ExtVT = VT;
7978   MVT EltVT = VT.getVectorElementType();
7979
7980   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7981                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7982                 Mask.begin();
7983   bool IsV1Zeroable = true;
7984   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7985     if (i != V2Index && !Zeroable[i]) {
7986       IsV1Zeroable = false;
7987       break;
7988     }
7989
7990   // Check for a single input from a SCALAR_TO_VECTOR node.
7991   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7992   // all the smarts here sunk into that routine. However, the current
7993   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7994   // vector shuffle lowering is dead.
7995   if (SDValue V2S = getScalarValueForVectorElement(
7996           V2, Mask[V2Index] - Mask.size(), DAG)) {
7997     // We need to zext the scalar if it is smaller than an i32.
7998     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7999     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
8000       // Using zext to expand a narrow element won't work for non-zero
8001       // insertions.
8002       if (!IsV1Zeroable)
8003         return SDValue();
8004
8005       // Zero-extend directly to i32.
8006       ExtVT = MVT::v4i32;
8007       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
8008     }
8009     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8010   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8011              EltVT == MVT::i16) {
8012     // Either not inserting from the low element of the input or the input
8013     // element size is too small to use VZEXT_MOVL to clear the high bits.
8014     return SDValue();
8015   }
8016
8017   if (!IsV1Zeroable) {
8018     // If V1 can't be treated as a zero vector we have fewer options to lower
8019     // this. We can't support integer vectors or non-zero targets cheaply, and
8020     // the V1 elements can't be permuted in any way.
8021     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8022     if (!VT.isFloatingPoint() || V2Index != 0)
8023       return SDValue();
8024     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8025     V1Mask[V2Index] = -1;
8026     if (!isNoopShuffleMask(V1Mask))
8027       return SDValue();
8028     // This is essentially a special case blend operation, but if we have
8029     // general purpose blend operations, they are always faster. Bail and let
8030     // the rest of the lowering handle these as blends.
8031     if (Subtarget->hasSSE41())
8032       return SDValue();
8033
8034     // Otherwise, use MOVSD or MOVSS.
8035     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8036            "Only two types of floating point element types to handle!");
8037     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8038                        ExtVT, V1, V2);
8039   }
8040
8041   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8042   if (ExtVT != VT)
8043     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8044
8045   if (V2Index != 0) {
8046     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8047     // the desired position. Otherwise it is more efficient to do a vector
8048     // shift left. We know that we can do a vector shift left because all
8049     // the inputs are zero.
8050     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8051       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8052       V2Shuffle[V2Index] = 0;
8053       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8054     } else {
8055       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
8056       V2 = DAG.getNode(
8057           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8058           DAG.getConstant(
8059               V2Index * EltVT.getSizeInBits(),
8060               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
8061       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8062     }
8063   }
8064   return V2;
8065 }
8066
8067 /// \brief Try to lower broadcast of a single element.
8068 ///
8069 /// For convenience, this code also bundles all of the subtarget feature set
8070 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8071 /// a convenient way to factor it out.
8072 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
8073                                              ArrayRef<int> Mask,
8074                                              const X86Subtarget *Subtarget,
8075                                              SelectionDAG &DAG) {
8076   if (!Subtarget->hasAVX())
8077     return SDValue();
8078   if (VT.isInteger() && !Subtarget->hasAVX2())
8079     return SDValue();
8080
8081   // Check that the mask is a broadcast.
8082   int BroadcastIdx = -1;
8083   for (int M : Mask)
8084     if (M >= 0 && BroadcastIdx == -1)
8085       BroadcastIdx = M;
8086     else if (M >= 0 && M != BroadcastIdx)
8087       return SDValue();
8088
8089   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8090                                             "a sorted mask where the broadcast "
8091                                             "comes from V1.");
8092
8093   // Go up the chain of (vector) values to try and find a scalar load that
8094   // we can combine with the broadcast.
8095   for (;;) {
8096     switch (V.getOpcode()) {
8097     case ISD::CONCAT_VECTORS: {
8098       int OperandSize = Mask.size() / V.getNumOperands();
8099       V = V.getOperand(BroadcastIdx / OperandSize);
8100       BroadcastIdx %= OperandSize;
8101       continue;
8102     }
8103
8104     case ISD::INSERT_SUBVECTOR: {
8105       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8106       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8107       if (!ConstantIdx)
8108         break;
8109
8110       int BeginIdx = (int)ConstantIdx->getZExtValue();
8111       int EndIdx =
8112           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
8113       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8114         BroadcastIdx -= BeginIdx;
8115         V = VInner;
8116       } else {
8117         V = VOuter;
8118       }
8119       continue;
8120     }
8121     }
8122     break;
8123   }
8124
8125   // Check if this is a broadcast of a scalar. We special case lowering
8126   // for scalars so that we can more effectively fold with loads.
8127   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8128       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8129     V = V.getOperand(BroadcastIdx);
8130
8131     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
8132     // AVX2.
8133     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8134       return SDValue();
8135   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8136     // We can't broadcast from a vector register w/o AVX2, and we can only
8137     // broadcast from the zero-element of a vector register.
8138     return SDValue();
8139   }
8140
8141   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8142 }
8143
8144 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8145 ///
8146 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8147 /// support for floating point shuffles but not integer shuffles. These
8148 /// instructions will incur a domain crossing penalty on some chips though so
8149 /// it is better to avoid lowering through this for integer vectors where
8150 /// possible.
8151 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8152                                        const X86Subtarget *Subtarget,
8153                                        SelectionDAG &DAG) {
8154   SDLoc DL(Op);
8155   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8156   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8157   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8158   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8159   ArrayRef<int> Mask = SVOp->getMask();
8160   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8161
8162   if (isSingleInputShuffleMask(Mask)) {
8163     // Straight shuffle of a single input vector. Simulate this by using the
8164     // single input as both of the "inputs" to this instruction..
8165     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8166
8167     if (Subtarget->hasAVX()) {
8168       // If we have AVX, we can use VPERMILPS which will allow folding a load
8169       // into the shuffle.
8170       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8171                          DAG.getConstant(SHUFPDMask, MVT::i8));
8172     }
8173
8174     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
8175                        DAG.getConstant(SHUFPDMask, MVT::i8));
8176   }
8177   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8178   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8179
8180   // Use dedicated unpack instructions for masks that match their pattern.
8181   if (isShuffleEquivalent(Mask, 0, 2))
8182     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8183   if (isShuffleEquivalent(Mask, 1, 3))
8184     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8185
8186   // If we have a single input, insert that into V1 if we can do so cheaply.
8187   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8188     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8189             MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
8190       return Insertion;
8191     // Try inverting the insertion since for v2 masks it is easy to do and we
8192     // can't reliably sort the mask one way or the other.
8193     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8194                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8195     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8196             MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
8197       return Insertion;
8198   }
8199
8200   // Try to use one of the special instruction patterns to handle two common
8201   // blend patterns if a zero-blend above didn't work.
8202   if (isShuffleEquivalent(Mask, 0, 3) || isShuffleEquivalent(Mask, 1, 3))
8203     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8204       // We can either use a special instruction to load over the low double or
8205       // to move just the low double.
8206       return DAG.getNode(
8207           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8208           DL, MVT::v2f64, V2,
8209           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8210
8211   if (Subtarget->hasSSE41())
8212     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8213                                                   Subtarget, DAG))
8214       return Blend;
8215
8216   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8217   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
8218                      DAG.getConstant(SHUFPDMask, MVT::i8));
8219 }
8220
8221 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8222 ///
8223 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8224 /// the integer unit to minimize domain crossing penalties. However, for blends
8225 /// it falls back to the floating point shuffle operation with appropriate bit
8226 /// casting.
8227 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8228                                        const X86Subtarget *Subtarget,
8229                                        SelectionDAG &DAG) {
8230   SDLoc DL(Op);
8231   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8232   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8233   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8234   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8235   ArrayRef<int> Mask = SVOp->getMask();
8236   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8237
8238   if (isSingleInputShuffleMask(Mask)) {
8239     // Check for being able to broadcast a single element.
8240     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
8241                                                           Mask, Subtarget, DAG))
8242       return Broadcast;
8243
8244     // Straight shuffle of a single input vector. For everything from SSE2
8245     // onward this has a single fast instruction with no scary immediates.
8246     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8247     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
8248     int WidenedMask[4] = {
8249         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8250         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8251     return DAG.getNode(
8252         ISD::BITCAST, DL, MVT::v2i64,
8253         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
8254                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
8255   }
8256
8257   // Try to use byte shift instructions.
8258   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8259           DL, MVT::v2i64, V1, V2, Mask, DAG))
8260     return Shift;
8261
8262   // If we have a single input from V2 insert that into V1 if we can do so
8263   // cheaply.
8264   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8265     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8266             MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
8267       return Insertion;
8268     // Try inverting the insertion since for v2 masks it is easy to do and we
8269     // can't reliably sort the mask one way or the other.
8270     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8271                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8272     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8273             MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
8274       return Insertion;
8275   }
8276
8277   // Use dedicated unpack instructions for masks that match their pattern.
8278   if (isShuffleEquivalent(Mask, 0, 2))
8279     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8280   if (isShuffleEquivalent(Mask, 1, 3))
8281     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8282
8283   if (Subtarget->hasSSE41())
8284     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8285                                                   Subtarget, DAG))
8286       return Blend;
8287
8288   // Try to use byte rotation instructions.
8289   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8290   if (Subtarget->hasSSSE3())
8291     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8292             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8293       return Rotate;
8294
8295   // We implement this with SHUFPD which is pretty lame because it will likely
8296   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8297   // However, all the alternatives are still more cycles and newer chips don't
8298   // have this problem. It would be really nice if x86 had better shuffles here.
8299   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
8300   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
8301   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
8302                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8303 }
8304
8305 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8306 ///
8307 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8308 /// It makes no assumptions about whether this is the *best* lowering, it simply
8309 /// uses it.
8310 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8311                                             ArrayRef<int> Mask, SDValue V1,
8312                                             SDValue V2, SelectionDAG &DAG) {
8313   SDValue LowV = V1, HighV = V2;
8314   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8315
8316   int NumV2Elements =
8317       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8318
8319   if (NumV2Elements == 1) {
8320     int V2Index =
8321         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8322         Mask.begin();
8323
8324     // Compute the index adjacent to V2Index and in the same half by toggling
8325     // the low bit.
8326     int V2AdjIndex = V2Index ^ 1;
8327
8328     if (Mask[V2AdjIndex] == -1) {
8329       // Handles all the cases where we have a single V2 element and an undef.
8330       // This will only ever happen in the high lanes because we commute the
8331       // vector otherwise.
8332       if (V2Index < 2)
8333         std::swap(LowV, HighV);
8334       NewMask[V2Index] -= 4;
8335     } else {
8336       // Handle the case where the V2 element ends up adjacent to a V1 element.
8337       // To make this work, blend them together as the first step.
8338       int V1Index = V2AdjIndex;
8339       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8340       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8341                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8342
8343       // Now proceed to reconstruct the final blend as we have the necessary
8344       // high or low half formed.
8345       if (V2Index < 2) {
8346         LowV = V2;
8347         HighV = V1;
8348       } else {
8349         HighV = V2;
8350       }
8351       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8352       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8353     }
8354   } else if (NumV2Elements == 2) {
8355     if (Mask[0] < 4 && Mask[1] < 4) {
8356       // Handle the easy case where we have V1 in the low lanes and V2 in the
8357       // high lanes.
8358       NewMask[2] -= 4;
8359       NewMask[3] -= 4;
8360     } else if (Mask[2] < 4 && Mask[3] < 4) {
8361       // We also handle the reversed case because this utility may get called
8362       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8363       // arrange things in the right direction.
8364       NewMask[0] -= 4;
8365       NewMask[1] -= 4;
8366       HighV = V1;
8367       LowV = V2;
8368     } else {
8369       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8370       // trying to place elements directly, just blend them and set up the final
8371       // shuffle to place them.
8372
8373       // The first two blend mask elements are for V1, the second two are for
8374       // V2.
8375       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8376                           Mask[2] < 4 ? Mask[2] : Mask[3],
8377                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8378                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8379       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8380                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8381
8382       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8383       // a blend.
8384       LowV = HighV = V1;
8385       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8386       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8387       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8388       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8389     }
8390   }
8391   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8392                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
8393 }
8394
8395 /// \brief Lower 4-lane 32-bit floating point shuffles.
8396 ///
8397 /// Uses instructions exclusively from the floating point unit to minimize
8398 /// domain crossing penalties, as these are sufficient to implement all v4f32
8399 /// shuffles.
8400 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8401                                        const X86Subtarget *Subtarget,
8402                                        SelectionDAG &DAG) {
8403   SDLoc DL(Op);
8404   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8405   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8406   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8407   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8408   ArrayRef<int> Mask = SVOp->getMask();
8409   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8410
8411   int NumV2Elements =
8412       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8413
8414   if (NumV2Elements == 0) {
8415     // Check for being able to broadcast a single element.
8416     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
8417                                                           Mask, Subtarget, DAG))
8418       return Broadcast;
8419
8420     if (Subtarget->hasAVX()) {
8421       // If we have AVX, we can use VPERMILPS which will allow folding a load
8422       // into the shuffle.
8423       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8424                          getV4X86ShuffleImm8ForMask(Mask, DAG));
8425     }
8426
8427     // Otherwise, use a straight shuffle of a single input vector. We pass the
8428     // input vector to both operands to simulate this with a SHUFPS.
8429     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8430                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8431   }
8432
8433   // Use dedicated unpack instructions for masks that match their pattern.
8434   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8435     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8436   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8437     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8438
8439   // There are special ways we can lower some single-element blends. However, we
8440   // have custom ways we can lower more complex single-element blends below that
8441   // we defer to if both this and BLENDPS fail to match, so restrict this to
8442   // when the V2 input is targeting element 0 of the mask -- that is the fast
8443   // case here.
8444   if (NumV2Elements == 1 && Mask[0] >= 4)
8445     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
8446                                                          Mask, Subtarget, DAG))
8447       return V;
8448
8449   if (Subtarget->hasSSE41())
8450     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8451                                                   Subtarget, DAG))
8452       return Blend;
8453
8454   // Check for whether we can use INSERTPS to perform the blend. We only use
8455   // INSERTPS when the V1 elements are already in the correct locations
8456   // because otherwise we can just always use two SHUFPS instructions which
8457   // are much smaller to encode than a SHUFPS and an INSERTPS.
8458   if (NumV2Elements == 1 && Subtarget->hasSSE41()) {
8459     int V2Index =
8460         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8461         Mask.begin();
8462
8463     // When using INSERTPS we can zero any lane of the destination. Collect
8464     // the zero inputs into a mask and drop them from the lanes of V1 which
8465     // actually need to be present as inputs to the INSERTPS.
8466     SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8467
8468     // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
8469     bool InsertNeedsShuffle = false;
8470     unsigned ZMask = 0;
8471     for (int i = 0; i < 4; ++i)
8472       if (i != V2Index) {
8473         if (Zeroable[i]) {
8474           ZMask |= 1 << i;
8475         } else if (Mask[i] != i) {
8476           InsertNeedsShuffle = true;
8477           break;
8478         }
8479       }
8480
8481     // We don't want to use INSERTPS or other insertion techniques if it will
8482     // require shuffling anyways.
8483     if (!InsertNeedsShuffle) {
8484       // If all of V1 is zeroable, replace it with undef.
8485       if ((ZMask | 1 << V2Index) == 0xF)
8486         V1 = DAG.getUNDEF(MVT::v4f32);
8487
8488       unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
8489       assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8490
8491       // Insert the V2 element into the desired position.
8492       return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8493                          DAG.getConstant(InsertPSMask, MVT::i8));
8494     }
8495   }
8496
8497   // Otherwise fall back to a SHUFPS lowering strategy.
8498   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8499 }
8500
8501 /// \brief Lower 4-lane i32 vector shuffles.
8502 ///
8503 /// We try to handle these with integer-domain shuffles where we can, but for
8504 /// blends we use the floating point domain blend instructions.
8505 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8506                                        const X86Subtarget *Subtarget,
8507                                        SelectionDAG &DAG) {
8508   SDLoc DL(Op);
8509   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8510   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8511   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8512   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8513   ArrayRef<int> Mask = SVOp->getMask();
8514   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8515
8516   // Whenever we can lower this as a zext, that instruction is strictly faster
8517   // than any alternative. It also allows us to fold memory operands into the
8518   // shuffle in many cases.
8519   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8520                                                          Mask, Subtarget, DAG))
8521     return ZExt;
8522
8523   int NumV2Elements =
8524       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8525
8526   if (NumV2Elements == 0) {
8527     // Check for being able to broadcast a single element.
8528     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
8529                                                           Mask, Subtarget, DAG))
8530       return Broadcast;
8531
8532     // Straight shuffle of a single input vector. For everything from SSE2
8533     // onward this has a single fast instruction with no scary immediates.
8534     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8535     // but we aren't actually going to use the UNPCK instruction because doing
8536     // so prevents folding a load into this instruction or making a copy.
8537     const int UnpackLoMask[] = {0, 0, 1, 1};
8538     const int UnpackHiMask[] = {2, 2, 3, 3};
8539     if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
8540       Mask = UnpackLoMask;
8541     else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
8542       Mask = UnpackHiMask;
8543
8544     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8545                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8546   }
8547
8548   // Try to use byte shift instructions.
8549   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8550           DL, MVT::v4i32, V1, V2, Mask, DAG))
8551     return Shift;
8552
8553   // There are special ways we can lower some single-element blends.
8554   if (NumV2Elements == 1)
8555     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
8556                                                          Mask, Subtarget, DAG))
8557       return V;
8558
8559   // Use dedicated unpack instructions for masks that match their pattern.
8560   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8561     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8562   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8563     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8564
8565   if (Subtarget->hasSSE41())
8566     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8567                                                   Subtarget, DAG))
8568       return Blend;
8569
8570   // Try to use byte rotation instructions.
8571   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8572   if (Subtarget->hasSSSE3())
8573     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8574             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8575       return Rotate;
8576
8577   // We implement this with SHUFPS because it can blend from two vectors.
8578   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8579   // up the inputs, bypassing domain shift penalties that we would encur if we
8580   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8581   // relevant.
8582   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
8583                      DAG.getVectorShuffle(
8584                          MVT::v4f32, DL,
8585                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
8586                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
8587 }
8588
8589 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8590 /// shuffle lowering, and the most complex part.
8591 ///
8592 /// The lowering strategy is to try to form pairs of input lanes which are
8593 /// targeted at the same half of the final vector, and then use a dword shuffle
8594 /// to place them onto the right half, and finally unpack the paired lanes into
8595 /// their final position.
8596 ///
8597 /// The exact breakdown of how to form these dword pairs and align them on the
8598 /// correct sides is really tricky. See the comments within the function for
8599 /// more of the details.
8600 static SDValue lowerV8I16SingleInputVectorShuffle(
8601     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
8602     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8603   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8604   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8605   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8606
8607   SmallVector<int, 4> LoInputs;
8608   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8609                [](int M) { return M >= 0; });
8610   std::sort(LoInputs.begin(), LoInputs.end());
8611   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8612   SmallVector<int, 4> HiInputs;
8613   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8614                [](int M) { return M >= 0; });
8615   std::sort(HiInputs.begin(), HiInputs.end());
8616   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8617   int NumLToL =
8618       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8619   int NumHToL = LoInputs.size() - NumLToL;
8620   int NumLToH =
8621       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8622   int NumHToH = HiInputs.size() - NumLToH;
8623   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8624   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8625   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8626   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8627
8628   // Check for being able to broadcast a single element.
8629   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
8630                                                         Mask, Subtarget, DAG))
8631     return Broadcast;
8632
8633   // Try to use byte shift instructions.
8634   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8635           DL, MVT::v8i16, V, V, Mask, DAG))
8636     return Shift;
8637
8638   // Use dedicated unpack instructions for masks that match their pattern.
8639   if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
8640     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
8641   if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
8642     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
8643
8644   // Try to use byte rotation instructions.
8645   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8646           DL, MVT::v8i16, V, V, Mask, Subtarget, DAG))
8647     return Rotate;
8648
8649   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8650   // such inputs we can swap two of the dwords across the half mark and end up
8651   // with <=2 inputs to each half in each half. Once there, we can fall through
8652   // to the generic code below. For example:
8653   //
8654   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8655   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8656   //
8657   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8658   // and an existing 2-into-2 on the other half. In this case we may have to
8659   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8660   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8661   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8662   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8663   // half than the one we target for fixing) will be fixed when we re-enter this
8664   // path. We will also combine away any sequence of PSHUFD instructions that
8665   // result into a single instruction. Here is an example of the tricky case:
8666   //
8667   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8668   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8669   //
8670   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8671   //
8672   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8673   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8674   //
8675   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8676   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8677   //
8678   // The result is fine to be handled by the generic logic.
8679   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8680                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8681                           int AOffset, int BOffset) {
8682     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8683            "Must call this with A having 3 or 1 inputs from the A half.");
8684     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8685            "Must call this with B having 1 or 3 inputs from the B half.");
8686     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8687            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8688
8689     // Compute the index of dword with only one word among the three inputs in
8690     // a half by taking the sum of the half with three inputs and subtracting
8691     // the sum of the actual three inputs. The difference is the remaining
8692     // slot.
8693     int ADWord, BDWord;
8694     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8695     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8696     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8697     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8698     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8699     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8700     int TripleNonInputIdx =
8701         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8702     TripleDWord = TripleNonInputIdx / 2;
8703
8704     // We use xor with one to compute the adjacent DWord to whichever one the
8705     // OneInput is in.
8706     OneInputDWord = (OneInput / 2) ^ 1;
8707
8708     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8709     // and BToA inputs. If there is also such a problem with the BToB and AToB
8710     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8711     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8712     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8713     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8714       // Compute how many inputs will be flipped by swapping these DWords. We
8715       // need
8716       // to balance this to ensure we don't form a 3-1 shuffle in the other
8717       // half.
8718       int NumFlippedAToBInputs =
8719           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8720           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8721       int NumFlippedBToBInputs =
8722           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8723           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8724       if ((NumFlippedAToBInputs == 1 &&
8725            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8726           (NumFlippedBToBInputs == 1 &&
8727            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8728         // We choose whether to fix the A half or B half based on whether that
8729         // half has zero flipped inputs. At zero, we may not be able to fix it
8730         // with that half. We also bias towards fixing the B half because that
8731         // will more commonly be the high half, and we have to bias one way.
8732         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8733                                                        ArrayRef<int> Inputs) {
8734           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8735           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8736                                          PinnedIdx ^ 1) != Inputs.end();
8737           // Determine whether the free index is in the flipped dword or the
8738           // unflipped dword based on where the pinned index is. We use this bit
8739           // in an xor to conditionally select the adjacent dword.
8740           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8741           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8742                                              FixFreeIdx) != Inputs.end();
8743           if (IsFixIdxInput == IsFixFreeIdxInput)
8744             FixFreeIdx += 1;
8745           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8746                                         FixFreeIdx) != Inputs.end();
8747           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8748                  "We need to be changing the number of flipped inputs!");
8749           int PSHUFHalfMask[] = {0, 1, 2, 3};
8750           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8751           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8752                           MVT::v8i16, V,
8753                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
8754
8755           for (int &M : Mask)
8756             if (M != -1 && M == FixIdx)
8757               M = FixFreeIdx;
8758             else if (M != -1 && M == FixFreeIdx)
8759               M = FixIdx;
8760         };
8761         if (NumFlippedBToBInputs != 0) {
8762           int BPinnedIdx =
8763               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8764           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8765         } else {
8766           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8767           int APinnedIdx =
8768               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8769           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8770         }
8771       }
8772     }
8773
8774     int PSHUFDMask[] = {0, 1, 2, 3};
8775     PSHUFDMask[ADWord] = BDWord;
8776     PSHUFDMask[BDWord] = ADWord;
8777     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8778                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8779                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8780                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8781
8782     // Adjust the mask to match the new locations of A and B.
8783     for (int &M : Mask)
8784       if (M != -1 && M/2 == ADWord)
8785         M = 2 * BDWord + M % 2;
8786       else if (M != -1 && M/2 == BDWord)
8787         M = 2 * ADWord + M % 2;
8788
8789     // Recurse back into this routine to re-compute state now that this isn't
8790     // a 3 and 1 problem.
8791     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8792                                 Mask);
8793   };
8794   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8795     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8796   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8797     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8798
8799   // At this point there are at most two inputs to the low and high halves from
8800   // each half. That means the inputs can always be grouped into dwords and
8801   // those dwords can then be moved to the correct half with a dword shuffle.
8802   // We use at most one low and one high word shuffle to collect these paired
8803   // inputs into dwords, and finally a dword shuffle to place them.
8804   int PSHUFLMask[4] = {-1, -1, -1, -1};
8805   int PSHUFHMask[4] = {-1, -1, -1, -1};
8806   int PSHUFDMask[4] = {-1, -1, -1, -1};
8807
8808   // First fix the masks for all the inputs that are staying in their
8809   // original halves. This will then dictate the targets of the cross-half
8810   // shuffles.
8811   auto fixInPlaceInputs =
8812       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8813                     MutableArrayRef<int> SourceHalfMask,
8814                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8815     if (InPlaceInputs.empty())
8816       return;
8817     if (InPlaceInputs.size() == 1) {
8818       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8819           InPlaceInputs[0] - HalfOffset;
8820       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8821       return;
8822     }
8823     if (IncomingInputs.empty()) {
8824       // Just fix all of the in place inputs.
8825       for (int Input : InPlaceInputs) {
8826         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8827         PSHUFDMask[Input / 2] = Input / 2;
8828       }
8829       return;
8830     }
8831
8832     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8833     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8834         InPlaceInputs[0] - HalfOffset;
8835     // Put the second input next to the first so that they are packed into
8836     // a dword. We find the adjacent index by toggling the low bit.
8837     int AdjIndex = InPlaceInputs[0] ^ 1;
8838     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8839     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8840     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8841   };
8842   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8843   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8844
8845   // Now gather the cross-half inputs and place them into a free dword of
8846   // their target half.
8847   // FIXME: This operation could almost certainly be simplified dramatically to
8848   // look more like the 3-1 fixing operation.
8849   auto moveInputsToRightHalf = [&PSHUFDMask](
8850       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8851       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8852       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8853       int DestOffset) {
8854     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8855       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8856     };
8857     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8858                                                int Word) {
8859       int LowWord = Word & ~1;
8860       int HighWord = Word | 1;
8861       return isWordClobbered(SourceHalfMask, LowWord) ||
8862              isWordClobbered(SourceHalfMask, HighWord);
8863     };
8864
8865     if (IncomingInputs.empty())
8866       return;
8867
8868     if (ExistingInputs.empty()) {
8869       // Map any dwords with inputs from them into the right half.
8870       for (int Input : IncomingInputs) {
8871         // If the source half mask maps over the inputs, turn those into
8872         // swaps and use the swapped lane.
8873         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8874           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8875             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8876                 Input - SourceOffset;
8877             // We have to swap the uses in our half mask in one sweep.
8878             for (int &M : HalfMask)
8879               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8880                 M = Input;
8881               else if (M == Input)
8882                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8883           } else {
8884             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8885                        Input - SourceOffset &&
8886                    "Previous placement doesn't match!");
8887           }
8888           // Note that this correctly re-maps both when we do a swap and when
8889           // we observe the other side of the swap above. We rely on that to
8890           // avoid swapping the members of the input list directly.
8891           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8892         }
8893
8894         // Map the input's dword into the correct half.
8895         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8896           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8897         else
8898           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8899                      Input / 2 &&
8900                  "Previous placement doesn't match!");
8901       }
8902
8903       // And just directly shift any other-half mask elements to be same-half
8904       // as we will have mirrored the dword containing the element into the
8905       // same position within that half.
8906       for (int &M : HalfMask)
8907         if (M >= SourceOffset && M < SourceOffset + 4) {
8908           M = M - SourceOffset + DestOffset;
8909           assert(M >= 0 && "This should never wrap below zero!");
8910         }
8911       return;
8912     }
8913
8914     // Ensure we have the input in a viable dword of its current half. This
8915     // is particularly tricky because the original position may be clobbered
8916     // by inputs being moved and *staying* in that half.
8917     if (IncomingInputs.size() == 1) {
8918       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8919         int InputFixed = std::find(std::begin(SourceHalfMask),
8920                                    std::end(SourceHalfMask), -1) -
8921                          std::begin(SourceHalfMask) + SourceOffset;
8922         SourceHalfMask[InputFixed - SourceOffset] =
8923             IncomingInputs[0] - SourceOffset;
8924         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8925                      InputFixed);
8926         IncomingInputs[0] = InputFixed;
8927       }
8928     } else if (IncomingInputs.size() == 2) {
8929       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8930           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8931         // We have two non-adjacent or clobbered inputs we need to extract from
8932         // the source half. To do this, we need to map them into some adjacent
8933         // dword slot in the source mask.
8934         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8935                               IncomingInputs[1] - SourceOffset};
8936
8937         // If there is a free slot in the source half mask adjacent to one of
8938         // the inputs, place the other input in it. We use (Index XOR 1) to
8939         // compute an adjacent index.
8940         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8941             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8942           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8943           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8944           InputsFixed[1] = InputsFixed[0] ^ 1;
8945         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8946                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8947           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8948           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8949           InputsFixed[0] = InputsFixed[1] ^ 1;
8950         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8951                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8952           // The two inputs are in the same DWord but it is clobbered and the
8953           // adjacent DWord isn't used at all. Move both inputs to the free
8954           // slot.
8955           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8956           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8957           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8958           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8959         } else {
8960           // The only way we hit this point is if there is no clobbering
8961           // (because there are no off-half inputs to this half) and there is no
8962           // free slot adjacent to one of the inputs. In this case, we have to
8963           // swap an input with a non-input.
8964           for (int i = 0; i < 4; ++i)
8965             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8966                    "We can't handle any clobbers here!");
8967           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8968                  "Cannot have adjacent inputs here!");
8969
8970           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8971           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8972
8973           // We also have to update the final source mask in this case because
8974           // it may need to undo the above swap.
8975           for (int &M : FinalSourceHalfMask)
8976             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8977               M = InputsFixed[1] + SourceOffset;
8978             else if (M == InputsFixed[1] + SourceOffset)
8979               M = (InputsFixed[0] ^ 1) + SourceOffset;
8980
8981           InputsFixed[1] = InputsFixed[0] ^ 1;
8982         }
8983
8984         // Point everything at the fixed inputs.
8985         for (int &M : HalfMask)
8986           if (M == IncomingInputs[0])
8987             M = InputsFixed[0] + SourceOffset;
8988           else if (M == IncomingInputs[1])
8989             M = InputsFixed[1] + SourceOffset;
8990
8991         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8992         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8993       }
8994     } else {
8995       llvm_unreachable("Unhandled input size!");
8996     }
8997
8998     // Now hoist the DWord down to the right half.
8999     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9000     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9001     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9002     for (int &M : HalfMask)
9003       for (int Input : IncomingInputs)
9004         if (M == Input)
9005           M = FreeDWord * 2 + Input % 2;
9006   };
9007   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9008                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9009   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9010                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9011
9012   // Now enact all the shuffles we've computed to move the inputs into their
9013   // target half.
9014   if (!isNoopShuffleMask(PSHUFLMask))
9015     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
9016                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
9017   if (!isNoopShuffleMask(PSHUFHMask))
9018     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
9019                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
9020   if (!isNoopShuffleMask(PSHUFDMask))
9021     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9022                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
9023                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
9024                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9025
9026   // At this point, each half should contain all its inputs, and we can then
9027   // just shuffle them into their final position.
9028   assert(std::count_if(LoMask.begin(), LoMask.end(),
9029                        [](int M) { return M >= 4; }) == 0 &&
9030          "Failed to lift all the high half inputs to the low mask!");
9031   assert(std::count_if(HiMask.begin(), HiMask.end(),
9032                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9033          "Failed to lift all the low half inputs to the high mask!");
9034
9035   // Do a half shuffle for the low mask.
9036   if (!isNoopShuffleMask(LoMask))
9037     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
9038                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
9039
9040   // Do a half shuffle with the high mask after shifting its values down.
9041   for (int &M : HiMask)
9042     if (M >= 0)
9043       M -= 4;
9044   if (!isNoopShuffleMask(HiMask))
9045     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
9046                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
9047
9048   return V;
9049 }
9050
9051 /// \brief Detect whether the mask pattern should be lowered through
9052 /// interleaving.
9053 ///
9054 /// This essentially tests whether viewing the mask as an interleaving of two
9055 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
9056 /// lowering it through interleaving is a significantly better strategy.
9057 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
9058   int NumEvenInputs[2] = {0, 0};
9059   int NumOddInputs[2] = {0, 0};
9060   int NumLoInputs[2] = {0, 0};
9061   int NumHiInputs[2] = {0, 0};
9062   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9063     if (Mask[i] < 0)
9064       continue;
9065
9066     int InputIdx = Mask[i] >= Size;
9067
9068     if (i < Size / 2)
9069       ++NumLoInputs[InputIdx];
9070     else
9071       ++NumHiInputs[InputIdx];
9072
9073     if ((i % 2) == 0)
9074       ++NumEvenInputs[InputIdx];
9075     else
9076       ++NumOddInputs[InputIdx];
9077   }
9078
9079   // The minimum number of cross-input results for both the interleaved and
9080   // split cases. If interleaving results in fewer cross-input results, return
9081   // true.
9082   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
9083                                     NumEvenInputs[0] + NumOddInputs[1]);
9084   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
9085                               NumLoInputs[0] + NumHiInputs[1]);
9086   return InterleavedCrosses < SplitCrosses;
9087 }
9088
9089 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
9090 ///
9091 /// This strategy only works when the inputs from each vector fit into a single
9092 /// half of that vector, and generally there are not so many inputs as to leave
9093 /// the in-place shuffles required highly constrained (and thus expensive). It
9094 /// shifts all the inputs into a single side of both input vectors and then
9095 /// uses an unpack to interleave these inputs in a single vector. At that
9096 /// point, we will fall back on the generic single input shuffle lowering.
9097 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
9098                                                  SDValue V2,
9099                                                  MutableArrayRef<int> Mask,
9100                                                  const X86Subtarget *Subtarget,
9101                                                  SelectionDAG &DAG) {
9102   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9103   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9104   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
9105   for (int i = 0; i < 8; ++i)
9106     if (Mask[i] >= 0 && Mask[i] < 4)
9107       LoV1Inputs.push_back(i);
9108     else if (Mask[i] >= 4 && Mask[i] < 8)
9109       HiV1Inputs.push_back(i);
9110     else if (Mask[i] >= 8 && Mask[i] < 12)
9111       LoV2Inputs.push_back(i);
9112     else if (Mask[i] >= 12)
9113       HiV2Inputs.push_back(i);
9114
9115   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
9116   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
9117   (void)NumV1Inputs;
9118   (void)NumV2Inputs;
9119   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
9120   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
9121   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
9122
9123   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
9124                      HiV1Inputs.size() + HiV2Inputs.size();
9125
9126   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
9127                               ArrayRef<int> HiInputs, bool MoveToLo,
9128                               int MaskOffset) {
9129     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
9130     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
9131     if (BadInputs.empty())
9132       return V;
9133
9134     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9135     int MoveOffset = MoveToLo ? 0 : 4;
9136
9137     if (GoodInputs.empty()) {
9138       for (int BadInput : BadInputs) {
9139         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
9140         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
9141       }
9142     } else {
9143       if (GoodInputs.size() == 2) {
9144         // If the low inputs are spread across two dwords, pack them into
9145         // a single dword.
9146         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
9147         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
9148         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
9149         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
9150       } else {
9151         // Otherwise pin the good inputs.
9152         for (int GoodInput : GoodInputs)
9153           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
9154       }
9155
9156       if (BadInputs.size() == 2) {
9157         // If we have two bad inputs then there may be either one or two good
9158         // inputs fixed in place. Find a fixed input, and then find the *other*
9159         // two adjacent indices by using modular arithmetic.
9160         int GoodMaskIdx =
9161             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
9162                          [](int M) { return M >= 0; }) -
9163             std::begin(MoveMask);
9164         int MoveMaskIdx =
9165             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
9166         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
9167         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
9168         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9169         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
9170         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9171         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
9172       } else {
9173         assert(BadInputs.size() == 1 && "All sizes handled");
9174         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
9175                                     std::end(MoveMask), -1) -
9176                           std::begin(MoveMask);
9177         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9178         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9179       }
9180     }
9181
9182     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
9183                                 MoveMask);
9184   };
9185   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
9186                         /*MaskOffset*/ 0);
9187   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
9188                         /*MaskOffset*/ 8);
9189
9190   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
9191   // cross-half traffic in the final shuffle.
9192
9193   // Munge the mask to be a single-input mask after the unpack merges the
9194   // results.
9195   for (int &M : Mask)
9196     if (M != -1)
9197       M = 2 * (M % 4) + (M / 8);
9198
9199   return DAG.getVectorShuffle(
9200       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
9201                                   DL, MVT::v8i16, V1, V2),
9202       DAG.getUNDEF(MVT::v8i16), Mask);
9203 }
9204
9205 /// \brief Generic lowering of 8-lane i16 shuffles.
9206 ///
9207 /// This handles both single-input shuffles and combined shuffle/blends with
9208 /// two inputs. The single input shuffles are immediately delegated to
9209 /// a dedicated lowering routine.
9210 ///
9211 /// The blends are lowered in one of three fundamental ways. If there are few
9212 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9213 /// of the input is significantly cheaper when lowered as an interleaving of
9214 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9215 /// halves of the inputs separately (making them have relatively few inputs)
9216 /// and then concatenate them.
9217 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9218                                        const X86Subtarget *Subtarget,
9219                                        SelectionDAG &DAG) {
9220   SDLoc DL(Op);
9221   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9222   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9223   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9224   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9225   ArrayRef<int> OrigMask = SVOp->getMask();
9226   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9227                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9228   MutableArrayRef<int> Mask(MaskStorage);
9229
9230   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9231
9232   // Whenever we can lower this as a zext, that instruction is strictly faster
9233   // than any alternative.
9234   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9235           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9236     return ZExt;
9237
9238   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9239   auto isV2 = [](int M) { return M >= 8; };
9240
9241   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
9242   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9243
9244   if (NumV2Inputs == 0)
9245     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
9246
9247   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
9248                             "to be V1-input shuffles.");
9249
9250   // Try to use byte shift instructions.
9251   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9252           DL, MVT::v8i16, V1, V2, Mask, DAG))
9253     return Shift;
9254
9255   // There are special ways we can lower some single-element blends.
9256   if (NumV2Inputs == 1)
9257     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
9258                                                          Mask, Subtarget, DAG))
9259       return V;
9260
9261   // Use dedicated unpack instructions for masks that match their pattern.
9262   if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 2, 10, 3, 11))
9263     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9264   if (isShuffleEquivalent(Mask, 4, 12, 5, 13, 6, 14, 7, 15))
9265     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9266
9267   if (Subtarget->hasSSE41())
9268     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9269                                                   Subtarget, DAG))
9270       return Blend;
9271
9272   // Try to use byte rotation instructions.
9273   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9274           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9275     return Rotate;
9276
9277   if (NumV1Inputs + NumV2Inputs <= 4)
9278     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
9279
9280   // Check whether an interleaving lowering is likely to be more efficient.
9281   // This isn't perfect but it is a strong heuristic that tends to work well on
9282   // the kinds of shuffles that show up in practice.
9283   //
9284   // FIXME: Handle 1x, 2x, and 4x interleaving.
9285   if (shouldLowerAsInterleaving(Mask)) {
9286     // FIXME: Figure out whether we should pack these into the low or high
9287     // halves.
9288
9289     int EMask[8], OMask[8];
9290     for (int i = 0; i < 4; ++i) {
9291       EMask[i] = Mask[2*i];
9292       OMask[i] = Mask[2*i + 1];
9293       EMask[i + 4] = -1;
9294       OMask[i + 4] = -1;
9295     }
9296
9297     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
9298     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
9299
9300     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
9301   }
9302
9303   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9304   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9305
9306   for (int i = 0; i < 4; ++i) {
9307     LoBlendMask[i] = Mask[i];
9308     HiBlendMask[i] = Mask[i + 4];
9309   }
9310
9311   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9312   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9313   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
9314   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
9315
9316   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9317                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
9318 }
9319
9320 /// \brief Check whether a compaction lowering can be done by dropping even
9321 /// elements and compute how many times even elements must be dropped.
9322 ///
9323 /// This handles shuffles which take every Nth element where N is a power of
9324 /// two. Example shuffle masks:
9325 ///
9326 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9327 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9328 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9329 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9330 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9331 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9332 ///
9333 /// Any of these lanes can of course be undef.
9334 ///
9335 /// This routine only supports N <= 3.
9336 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9337 /// for larger N.
9338 ///
9339 /// \returns N above, or the number of times even elements must be dropped if
9340 /// there is such a number. Otherwise returns zero.
9341 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9342   // Figure out whether we're looping over two inputs or just one.
9343   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9344
9345   // The modulus for the shuffle vector entries is based on whether this is
9346   // a single input or not.
9347   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9348   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9349          "We should only be called with masks with a power-of-2 size!");
9350
9351   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9352
9353   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9354   // and 2^3 simultaneously. This is because we may have ambiguity with
9355   // partially undef inputs.
9356   bool ViableForN[3] = {true, true, true};
9357
9358   for (int i = 0, e = Mask.size(); i < e; ++i) {
9359     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9360     // want.
9361     if (Mask[i] == -1)
9362       continue;
9363
9364     bool IsAnyViable = false;
9365     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9366       if (ViableForN[j]) {
9367         uint64_t N = j + 1;
9368
9369         // The shuffle mask must be equal to (i * 2^N) % M.
9370         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9371           IsAnyViable = true;
9372         else
9373           ViableForN[j] = false;
9374       }
9375     // Early exit if we exhaust the possible powers of two.
9376     if (!IsAnyViable)
9377       break;
9378   }
9379
9380   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9381     if (ViableForN[j])
9382       return j + 1;
9383
9384   // Return 0 as there is no viable power of two.
9385   return 0;
9386 }
9387
9388 /// \brief Generic lowering of v16i8 shuffles.
9389 ///
9390 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9391 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9392 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9393 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9394 /// back together.
9395 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9396                                        const X86Subtarget *Subtarget,
9397                                        SelectionDAG &DAG) {
9398   SDLoc DL(Op);
9399   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9400   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9401   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9402   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9403   ArrayRef<int> OrigMask = SVOp->getMask();
9404   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9405
9406   // Try to use byte shift instructions.
9407   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9408           DL, MVT::v16i8, V1, V2, OrigMask, DAG))
9409     return Shift;
9410
9411   // Try to use byte rotation instructions.
9412   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9413           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9414     return Rotate;
9415
9416   // Try to use a zext lowering.
9417   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9418           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9419     return ZExt;
9420
9421   int MaskStorage[16] = {
9422       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
9423       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
9424       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
9425       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
9426   MutableArrayRef<int> Mask(MaskStorage);
9427   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
9428   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
9429
9430   int NumV2Elements =
9431       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9432
9433   // For single-input shuffles, there are some nicer lowering tricks we can use.
9434   if (NumV2Elements == 0) {
9435     // Check for being able to broadcast a single element.
9436     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
9437                                                           Mask, Subtarget, DAG))
9438       return Broadcast;
9439
9440     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9441     // Notably, this handles splat and partial-splat shuffles more efficiently.
9442     // However, it only makes sense if the pre-duplication shuffle simplifies
9443     // things significantly. Currently, this means we need to be able to
9444     // express the pre-duplication shuffle as an i16 shuffle.
9445     //
9446     // FIXME: We should check for other patterns which can be widened into an
9447     // i16 shuffle as well.
9448     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9449       for (int i = 0; i < 16; i += 2)
9450         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9451           return false;
9452
9453       return true;
9454     };
9455     auto tryToWidenViaDuplication = [&]() -> SDValue {
9456       if (!canWidenViaDuplication(Mask))
9457         return SDValue();
9458       SmallVector<int, 4> LoInputs;
9459       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9460                    [](int M) { return M >= 0 && M < 8; });
9461       std::sort(LoInputs.begin(), LoInputs.end());
9462       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9463                      LoInputs.end());
9464       SmallVector<int, 4> HiInputs;
9465       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9466                    [](int M) { return M >= 8; });
9467       std::sort(HiInputs.begin(), HiInputs.end());
9468       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9469                      HiInputs.end());
9470
9471       bool TargetLo = LoInputs.size() >= HiInputs.size();
9472       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9473       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9474
9475       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9476       SmallDenseMap<int, int, 8> LaneMap;
9477       for (int I : InPlaceInputs) {
9478         PreDupI16Shuffle[I/2] = I/2;
9479         LaneMap[I] = I;
9480       }
9481       int j = TargetLo ? 0 : 4, je = j + 4;
9482       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9483         // Check if j is already a shuffle of this input. This happens when
9484         // there are two adjacent bytes after we move the low one.
9485         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9486           // If we haven't yet mapped the input, search for a slot into which
9487           // we can map it.
9488           while (j < je && PreDupI16Shuffle[j] != -1)
9489             ++j;
9490
9491           if (j == je)
9492             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9493             return SDValue();
9494
9495           // Map this input with the i16 shuffle.
9496           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9497         }
9498
9499         // Update the lane map based on the mapping we ended up with.
9500         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9501       }
9502       V1 = DAG.getNode(
9503           ISD::BITCAST, DL, MVT::v16i8,
9504           DAG.getVectorShuffle(MVT::v8i16, DL,
9505                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9506                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9507
9508       // Unpack the bytes to form the i16s that will be shuffled into place.
9509       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9510                        MVT::v16i8, V1, V1);
9511
9512       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9513       for (int i = 0; i < 16; ++i)
9514         if (Mask[i] != -1) {
9515           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9516           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9517           if (PostDupI16Shuffle[i / 2] == -1)
9518             PostDupI16Shuffle[i / 2] = MappedMask;
9519           else
9520             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9521                    "Conflicting entrties in the original shuffle!");
9522         }
9523       return DAG.getNode(
9524           ISD::BITCAST, DL, MVT::v16i8,
9525           DAG.getVectorShuffle(MVT::v8i16, DL,
9526                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9527                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9528     };
9529     if (SDValue V = tryToWidenViaDuplication())
9530       return V;
9531   }
9532
9533   // Check whether an interleaving lowering is likely to be more efficient.
9534   // This isn't perfect but it is a strong heuristic that tends to work well on
9535   // the kinds of shuffles that show up in practice.
9536   //
9537   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
9538   if (shouldLowerAsInterleaving(Mask)) {
9539     int NumLoHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9540       return (M >= 0 && M < 8) || (M >= 16 && M < 24);
9541     });
9542     int NumHiHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9543       return (M >= 8 && M < 16) || M >= 24;
9544     });
9545     int EMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9546                      -1, -1, -1, -1, -1, -1, -1, -1};
9547     int OMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9548                      -1, -1, -1, -1, -1, -1, -1, -1};
9549     bool UnpackLo = NumLoHalf >= NumHiHalf;
9550     MutableArrayRef<int> TargetEMask(UnpackLo ? EMask : EMask + 8, 8);
9551     MutableArrayRef<int> TargetOMask(UnpackLo ? OMask : OMask + 8, 8);
9552     for (int i = 0; i < 8; ++i) {
9553       TargetEMask[i] = Mask[2 * i];
9554       TargetOMask[i] = Mask[2 * i + 1];
9555     }
9556
9557     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
9558     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
9559
9560     return DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9561                        MVT::v16i8, Evens, Odds);
9562   }
9563
9564   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9565   // with PSHUFB. It is important to do this before we attempt to generate any
9566   // blends but after all of the single-input lowerings. If the single input
9567   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9568   // want to preserve that and we can DAG combine any longer sequences into
9569   // a PSHUFB in the end. But once we start blending from multiple inputs,
9570   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9571   // and there are *very* few patterns that would actually be faster than the
9572   // PSHUFB approach because of its ability to zero lanes.
9573   //
9574   // FIXME: The only exceptions to the above are blends which are exact
9575   // interleavings with direct instructions supporting them. We currently don't
9576   // handle those well here.
9577   if (Subtarget->hasSSSE3()) {
9578     SDValue V1Mask[16];
9579     SDValue V2Mask[16];
9580     for (int i = 0; i < 16; ++i)
9581       if (Mask[i] == -1) {
9582         V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9583       } else {
9584         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
9585         V2Mask[i] =
9586             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
9587       }
9588     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
9589                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9590     if (isSingleInputShuffleMask(Mask))
9591       return V1; // Single inputs are easy.
9592
9593     // Otherwise, blend the two.
9594     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
9595                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9596     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9597   }
9598
9599   // There are special ways we can lower some single-element blends.
9600   if (NumV2Elements == 1)
9601     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
9602                                                          Mask, Subtarget, DAG))
9603       return V;
9604
9605   // Check whether a compaction lowering can be done. This handles shuffles
9606   // which take every Nth element for some even N. See the helper function for
9607   // details.
9608   //
9609   // We special case these as they can be particularly efficiently handled with
9610   // the PACKUSB instruction on x86 and they show up in common patterns of
9611   // rearranging bytes to truncate wide elements.
9612   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9613     // NumEvenDrops is the power of two stride of the elements. Another way of
9614     // thinking about it is that we need to drop the even elements this many
9615     // times to get the original input.
9616     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9617
9618     // First we need to zero all the dropped bytes.
9619     assert(NumEvenDrops <= 3 &&
9620            "No support for dropping even elements more than 3 times.");
9621     // We use the mask type to pick which bytes are preserved based on how many
9622     // elements are dropped.
9623     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9624     SDValue ByteClearMask =
9625         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
9626                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
9627     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9628     if (!IsSingleInput)
9629       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9630
9631     // Now pack things back together.
9632     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
9633     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
9634     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9635     for (int i = 1; i < NumEvenDrops; ++i) {
9636       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
9637       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9638     }
9639
9640     return Result;
9641   }
9642
9643   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9644   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9645   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9646   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9647
9648   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
9649                             MutableArrayRef<int> V1HalfBlendMask,
9650                             MutableArrayRef<int> V2HalfBlendMask) {
9651     for (int i = 0; i < 8; ++i)
9652       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
9653         V1HalfBlendMask[i] = HalfMask[i];
9654         HalfMask[i] = i;
9655       } else if (HalfMask[i] >= 16) {
9656         V2HalfBlendMask[i] = HalfMask[i] - 16;
9657         HalfMask[i] = i + 8;
9658       }
9659   };
9660   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
9661   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
9662
9663   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9664
9665   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
9666                              MutableArrayRef<int> HiBlendMask) {
9667     SDValue V1, V2;
9668     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9669     // them out and avoid using UNPCK{L,H} to extract the elements of V as
9670     // i16s.
9671     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
9672                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
9673         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
9674                      [](int M) { return M >= 0 && M % 2 == 1; })) {
9675       // Use a mask to drop the high bytes.
9676       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
9677       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
9678                        DAG.getConstant(0x00FF, MVT::v8i16));
9679
9680       // This will be a single vector shuffle instead of a blend so nuke V2.
9681       V2 = DAG.getUNDEF(MVT::v8i16);
9682
9683       // Squash the masks to point directly into V1.
9684       for (int &M : LoBlendMask)
9685         if (M >= 0)
9686           M /= 2;
9687       for (int &M : HiBlendMask)
9688         if (M >= 0)
9689           M /= 2;
9690     } else {
9691       // Otherwise just unpack the low half of V into V1 and the high half into
9692       // V2 so that we can blend them as i16s.
9693       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9694                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9695       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9696                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9697     }
9698
9699     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9700     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9701     return std::make_pair(BlendedLo, BlendedHi);
9702   };
9703   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
9704   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
9705   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
9706
9707   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
9708   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
9709
9710   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9711 }
9712
9713 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9714 ///
9715 /// This routine breaks down the specific type of 128-bit shuffle and
9716 /// dispatches to the lowering routines accordingly.
9717 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9718                                         MVT VT, const X86Subtarget *Subtarget,
9719                                         SelectionDAG &DAG) {
9720   switch (VT.SimpleTy) {
9721   case MVT::v2i64:
9722     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9723   case MVT::v2f64:
9724     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9725   case MVT::v4i32:
9726     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9727   case MVT::v4f32:
9728     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9729   case MVT::v8i16:
9730     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9731   case MVT::v16i8:
9732     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9733
9734   default:
9735     llvm_unreachable("Unimplemented!");
9736   }
9737 }
9738
9739 /// \brief Helper function to test whether a shuffle mask could be
9740 /// simplified by widening the elements being shuffled.
9741 ///
9742 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9743 /// leaves it in an unspecified state.
9744 ///
9745 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9746 /// shuffle masks. The latter have the special property of a '-2' representing
9747 /// a zero-ed lane of a vector.
9748 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9749                                     SmallVectorImpl<int> &WidenedMask) {
9750   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9751     // If both elements are undef, its trivial.
9752     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9753       WidenedMask.push_back(SM_SentinelUndef);
9754       continue;
9755     }
9756
9757     // Check for an undef mask and a mask value properly aligned to fit with
9758     // a pair of values. If we find such a case, use the non-undef mask's value.
9759     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9760       WidenedMask.push_back(Mask[i + 1] / 2);
9761       continue;
9762     }
9763     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9764       WidenedMask.push_back(Mask[i] / 2);
9765       continue;
9766     }
9767
9768     // When zeroing, we need to spread the zeroing across both lanes to widen.
9769     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9770       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9771           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9772         WidenedMask.push_back(SM_SentinelZero);
9773         continue;
9774       }
9775       return false;
9776     }
9777
9778     // Finally check if the two mask values are adjacent and aligned with
9779     // a pair.
9780     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9781       WidenedMask.push_back(Mask[i] / 2);
9782       continue;
9783     }
9784
9785     // Otherwise we can't safely widen the elements used in this shuffle.
9786     return false;
9787   }
9788   assert(WidenedMask.size() == Mask.size() / 2 &&
9789          "Incorrect size of mask after widening the elements!");
9790
9791   return true;
9792 }
9793
9794 /// \brief Generic routine to split ector shuffle into half-sized shuffles.
9795 ///
9796 /// This routine just extracts two subvectors, shuffles them independently, and
9797 /// then concatenates them back together. This should work effectively with all
9798 /// AVX vector shuffle types.
9799 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9800                                           SDValue V2, ArrayRef<int> Mask,
9801                                           SelectionDAG &DAG) {
9802   assert(VT.getSizeInBits() >= 256 &&
9803          "Only for 256-bit or wider vector shuffles!");
9804   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9805   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9806
9807   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9808   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9809
9810   int NumElements = VT.getVectorNumElements();
9811   int SplitNumElements = NumElements / 2;
9812   MVT ScalarVT = VT.getScalarType();
9813   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9814
9815   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9816                              DAG.getIntPtrConstant(0));
9817   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9818                              DAG.getIntPtrConstant(SplitNumElements));
9819   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9820                              DAG.getIntPtrConstant(0));
9821   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9822                              DAG.getIntPtrConstant(SplitNumElements));
9823
9824   // Now create two 4-way blends of these half-width vectors.
9825   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9826     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9827     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9828     for (int i = 0; i < SplitNumElements; ++i) {
9829       int M = HalfMask[i];
9830       if (M >= NumElements) {
9831         if (M >= NumElements + SplitNumElements)
9832           UseHiV2 = true;
9833         else
9834           UseLoV2 = true;
9835         V2BlendMask.push_back(M - NumElements);
9836         V1BlendMask.push_back(-1);
9837         BlendMask.push_back(SplitNumElements + i);
9838       } else if (M >= 0) {
9839         if (M >= SplitNumElements)
9840           UseHiV1 = true;
9841         else
9842           UseLoV1 = true;
9843         V2BlendMask.push_back(-1);
9844         V1BlendMask.push_back(M);
9845         BlendMask.push_back(i);
9846       } else {
9847         V2BlendMask.push_back(-1);
9848         V1BlendMask.push_back(-1);
9849         BlendMask.push_back(-1);
9850       }
9851     }
9852
9853     // Because the lowering happens after all combining takes place, we need to
9854     // manually combine these blend masks as much as possible so that we create
9855     // a minimal number of high-level vector shuffle nodes.
9856
9857     // First try just blending the halves of V1 or V2.
9858     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9859       return DAG.getUNDEF(SplitVT);
9860     if (!UseLoV2 && !UseHiV2)
9861       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9862     if (!UseLoV1 && !UseHiV1)
9863       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9864
9865     SDValue V1Blend, V2Blend;
9866     if (UseLoV1 && UseHiV1) {
9867       V1Blend =
9868         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9869     } else {
9870       // We only use half of V1 so map the usage down into the final blend mask.
9871       V1Blend = UseLoV1 ? LoV1 : HiV1;
9872       for (int i = 0; i < SplitNumElements; ++i)
9873         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9874           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9875     }
9876     if (UseLoV2 && UseHiV2) {
9877       V2Blend =
9878         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9879     } else {
9880       // We only use half of V2 so map the usage down into the final blend mask.
9881       V2Blend = UseLoV2 ? LoV2 : HiV2;
9882       for (int i = 0; i < SplitNumElements; ++i)
9883         if (BlendMask[i] >= SplitNumElements)
9884           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9885     }
9886     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9887   };
9888   SDValue Lo = HalfBlend(LoMask);
9889   SDValue Hi = HalfBlend(HiMask);
9890   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9891 }
9892
9893 /// \brief Either split a vector in halves or decompose the shuffles and the
9894 /// blend.
9895 ///
9896 /// This is provided as a good fallback for many lowerings of non-single-input
9897 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9898 /// between splitting the shuffle into 128-bit components and stitching those
9899 /// back together vs. extracting the single-input shuffles and blending those
9900 /// results.
9901 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9902                                                 SDValue V2, ArrayRef<int> Mask,
9903                                                 SelectionDAG &DAG) {
9904   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9905                                             "lower single-input shuffles as it "
9906                                             "could then recurse on itself.");
9907   int Size = Mask.size();
9908
9909   // If this can be modeled as a broadcast of two elements followed by a blend,
9910   // prefer that lowering. This is especially important because broadcasts can
9911   // often fold with memory operands.
9912   auto DoBothBroadcast = [&] {
9913     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9914     for (int M : Mask)
9915       if (M >= Size) {
9916         if (V2BroadcastIdx == -1)
9917           V2BroadcastIdx = M - Size;
9918         else if (M - Size != V2BroadcastIdx)
9919           return false;
9920       } else if (M >= 0) {
9921         if (V1BroadcastIdx == -1)
9922           V1BroadcastIdx = M;
9923         else if (M != V1BroadcastIdx)
9924           return false;
9925       }
9926     return true;
9927   };
9928   if (DoBothBroadcast())
9929     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9930                                                       DAG);
9931
9932   // If the inputs all stem from a single 128-bit lane of each input, then we
9933   // split them rather than blending because the split will decompose to
9934   // unusually few instructions.
9935   int LaneCount = VT.getSizeInBits() / 128;
9936   int LaneSize = Size / LaneCount;
9937   SmallBitVector LaneInputs[2];
9938   LaneInputs[0].resize(LaneCount, false);
9939   LaneInputs[1].resize(LaneCount, false);
9940   for (int i = 0; i < Size; ++i)
9941     if (Mask[i] >= 0)
9942       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9943   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9944     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9945
9946   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9947   // that the decomposed single-input shuffles don't end up here.
9948   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9949 }
9950
9951 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9952 /// a permutation and blend of those lanes.
9953 ///
9954 /// This essentially blends the out-of-lane inputs to each lane into the lane
9955 /// from a permuted copy of the vector. This lowering strategy results in four
9956 /// instructions in the worst case for a single-input cross lane shuffle which
9957 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9958 /// of. Special cases for each particular shuffle pattern should be handled
9959 /// prior to trying this lowering.
9960 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9961                                                        SDValue V1, SDValue V2,
9962                                                        ArrayRef<int> Mask,
9963                                                        SelectionDAG &DAG) {
9964   // FIXME: This should probably be generalized for 512-bit vectors as well.
9965   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9966   int LaneSize = Mask.size() / 2;
9967
9968   // If there are only inputs from one 128-bit lane, splitting will in fact be
9969   // less expensive. The flags track wether the given lane contains an element
9970   // that crosses to another lane.
9971   bool LaneCrossing[2] = {false, false};
9972   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9973     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9974       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9975   if (!LaneCrossing[0] || !LaneCrossing[1])
9976     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9977
9978   if (isSingleInputShuffleMask(Mask)) {
9979     SmallVector<int, 32> FlippedBlendMask;
9980     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9981       FlippedBlendMask.push_back(
9982           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9983                                   ? Mask[i]
9984                                   : Mask[i] % LaneSize +
9985                                         (i / LaneSize) * LaneSize + Size));
9986
9987     // Flip the vector, and blend the results which should now be in-lane. The
9988     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9989     // 5 for the high source. The value 3 selects the high half of source 2 and
9990     // the value 2 selects the low half of source 2. We only use source 2 to
9991     // allow folding it into a memory operand.
9992     unsigned PERMMask = 3 | 2 << 4;
9993     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9994                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9995     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9996   }
9997
9998   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9999   // will be handled by the above logic and a blend of the results, much like
10000   // other patterns in AVX.
10001   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10002 }
10003
10004 /// \brief Handle lowering 2-lane 128-bit shuffles.
10005 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10006                                         SDValue V2, ArrayRef<int> Mask,
10007                                         const X86Subtarget *Subtarget,
10008                                         SelectionDAG &DAG) {
10009   // Blends are faster and handle all the non-lane-crossing cases.
10010   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10011                                                 Subtarget, DAG))
10012     return Blend;
10013
10014   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10015                                VT.getVectorNumElements() / 2);
10016   // Check for patterns which can be matched with a single insert of a 128-bit
10017   // subvector.
10018   if (isShuffleEquivalent(Mask, 0, 1, 0, 1) ||
10019       isShuffleEquivalent(Mask, 0, 1, 4, 5)) {
10020     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10021                               DAG.getIntPtrConstant(0));
10022     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10023                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
10024     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10025   }
10026   if (isShuffleEquivalent(Mask, 0, 1, 6, 7)) {
10027     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10028                               DAG.getIntPtrConstant(0));
10029     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
10030                               DAG.getIntPtrConstant(2));
10031     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10032   }
10033
10034   // Otherwise form a 128-bit permutation.
10035   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
10036   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
10037   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10038                      DAG.getConstant(PermMask, MVT::i8));
10039 }
10040
10041 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10042 /// shuffling each lane.
10043 ///
10044 /// This will only succeed when the result of fixing the 128-bit lanes results
10045 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10046 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10047 /// the lane crosses early and then use simpler shuffles within each lane.
10048 ///
10049 /// FIXME: It might be worthwhile at some point to support this without
10050 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10051 /// in x86 only floating point has interesting non-repeating shuffles, and even
10052 /// those are still *marginally* more expensive.
10053 static SDValue lowerVectorShuffleByMerging128BitLanes(
10054     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10055     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10056   assert(!isSingleInputShuffleMask(Mask) &&
10057          "This is only useful with multiple inputs.");
10058
10059   int Size = Mask.size();
10060   int LaneSize = 128 / VT.getScalarSizeInBits();
10061   int NumLanes = Size / LaneSize;
10062   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10063
10064   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10065   // check whether the in-128-bit lane shuffles share a repeating pattern.
10066   SmallVector<int, 4> Lanes;
10067   Lanes.resize(NumLanes, -1);
10068   SmallVector<int, 4> InLaneMask;
10069   InLaneMask.resize(LaneSize, -1);
10070   for (int i = 0; i < Size; ++i) {
10071     if (Mask[i] < 0)
10072       continue;
10073
10074     int j = i / LaneSize;
10075
10076     if (Lanes[j] < 0) {
10077       // First entry we've seen for this lane.
10078       Lanes[j] = Mask[i] / LaneSize;
10079     } else if (Lanes[j] != Mask[i] / LaneSize) {
10080       // This doesn't match the lane selected previously!
10081       return SDValue();
10082     }
10083
10084     // Check that within each lane we have a consistent shuffle mask.
10085     int k = i % LaneSize;
10086     if (InLaneMask[k] < 0) {
10087       InLaneMask[k] = Mask[i] % LaneSize;
10088     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10089       // This doesn't fit a repeating in-lane mask.
10090       return SDValue();
10091     }
10092   }
10093
10094   // First shuffle the lanes into place.
10095   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10096                                 VT.getSizeInBits() / 64);
10097   SmallVector<int, 8> LaneMask;
10098   LaneMask.resize(NumLanes * 2, -1);
10099   for (int i = 0; i < NumLanes; ++i)
10100     if (Lanes[i] >= 0) {
10101       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10102       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10103     }
10104
10105   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
10106   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
10107   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10108
10109   // Cast it back to the type we actually want.
10110   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
10111
10112   // Now do a simple shuffle that isn't lane crossing.
10113   SmallVector<int, 8> NewMask;
10114   NewMask.resize(Size, -1);
10115   for (int i = 0; i < Size; ++i)
10116     if (Mask[i] >= 0)
10117       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10118   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10119          "Must not introduce lane crosses at this point!");
10120
10121   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10122 }
10123
10124 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10125 /// given mask.
10126 ///
10127 /// This returns true if the elements from a particular input are already in the
10128 /// slot required by the given mask and require no permutation.
10129 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10130   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10131   int Size = Mask.size();
10132   for (int i = 0; i < Size; ++i)
10133     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10134       return false;
10135
10136   return true;
10137 }
10138
10139 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10140 ///
10141 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10142 /// isn't available.
10143 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10144                                        const X86Subtarget *Subtarget,
10145                                        SelectionDAG &DAG) {
10146   SDLoc DL(Op);
10147   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10148   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10149   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10150   ArrayRef<int> Mask = SVOp->getMask();
10151   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10152
10153   SmallVector<int, 4> WidenedMask;
10154   if (canWidenShuffleElements(Mask, WidenedMask))
10155     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10156                                     DAG);
10157
10158   if (isSingleInputShuffleMask(Mask)) {
10159     // Check for being able to broadcast a single element.
10160     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
10161                                                           Mask, Subtarget, DAG))
10162       return Broadcast;
10163
10164     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10165       // Non-half-crossing single input shuffles can be lowerid with an
10166       // interleaved permutation.
10167       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10168                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10169       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10170                          DAG.getConstant(VPERMILPMask, MVT::i8));
10171     }
10172
10173     // With AVX2 we have direct support for this permutation.
10174     if (Subtarget->hasAVX2())
10175       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10176                          getV4X86ShuffleImm8ForMask(Mask, DAG));
10177
10178     // Otherwise, fall back.
10179     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10180                                                    DAG);
10181   }
10182
10183   // X86 has dedicated unpack instructions that can handle specific blend
10184   // operations: UNPCKH and UNPCKL.
10185   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10186     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10187   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10188     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10189
10190   // If we have a single input to the zero element, insert that into V1 if we
10191   // can do so cheaply.
10192   int NumV2Elements =
10193       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
10194   if (NumV2Elements == 1 && Mask[0] >= 4)
10195     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10196             MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
10197       return Insertion;
10198
10199   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10200                                                 Subtarget, DAG))
10201     return Blend;
10202
10203   // Check if the blend happens to exactly fit that of SHUFPD.
10204   if ((Mask[0] == -1 || Mask[0] < 2) &&
10205       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
10206       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
10207       (Mask[3] == -1 || Mask[3] >= 6)) {
10208     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
10209                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
10210     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
10211                        DAG.getConstant(SHUFPDMask, MVT::i8));
10212   }
10213   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
10214       (Mask[1] == -1 || Mask[1] < 2) &&
10215       (Mask[2] == -1 || Mask[2] >= 6) &&
10216       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
10217     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
10218                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
10219     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
10220                        DAG.getConstant(SHUFPDMask, MVT::i8));
10221   }
10222
10223   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10224   // shuffle. However, if we have AVX2 and either inputs are already in place,
10225   // we will be able to shuffle even across lanes the other input in a single
10226   // instruction so skip this pattern.
10227   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10228                                  isShuffleMaskInputInPlace(1, Mask))))
10229     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10230             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10231       return Result;
10232
10233   // If we have AVX2 then we always want to lower with a blend because an v4 we
10234   // can fully permute the elements.
10235   if (Subtarget->hasAVX2())
10236     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10237                                                       Mask, DAG);
10238
10239   // Otherwise fall back on generic lowering.
10240   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10241 }
10242
10243 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10244 ///
10245 /// This routine is only called when we have AVX2 and thus a reasonable
10246 /// instruction set for v4i64 shuffling..
10247 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10248                                        const X86Subtarget *Subtarget,
10249                                        SelectionDAG &DAG) {
10250   SDLoc DL(Op);
10251   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10252   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10253   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10254   ArrayRef<int> Mask = SVOp->getMask();
10255   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10256   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10257
10258   SmallVector<int, 4> WidenedMask;
10259   if (canWidenShuffleElements(Mask, WidenedMask))
10260     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10261                                     DAG);
10262
10263   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10264                                                 Subtarget, DAG))
10265     return Blend;
10266
10267   // Check for being able to broadcast a single element.
10268   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
10269                                                         Mask, Subtarget, DAG))
10270     return Broadcast;
10271
10272   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10273   // use lower latency instructions that will operate on both 128-bit lanes.
10274   SmallVector<int, 2> RepeatedMask;
10275   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10276     if (isSingleInputShuffleMask(Mask)) {
10277       int PSHUFDMask[] = {-1, -1, -1, -1};
10278       for (int i = 0; i < 2; ++i)
10279         if (RepeatedMask[i] >= 0) {
10280           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10281           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10282         }
10283       return DAG.getNode(
10284           ISD::BITCAST, DL, MVT::v4i64,
10285           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10286                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
10287                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
10288     }
10289
10290     // Use dedicated unpack instructions for masks that match their pattern.
10291     if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10292       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10293     if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10294       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10295   }
10296
10297   // AVX2 provides a direct instruction for permuting a single input across
10298   // lanes.
10299   if (isSingleInputShuffleMask(Mask))
10300     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10301                        getV4X86ShuffleImm8ForMask(Mask, DAG));
10302
10303   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10304   // shuffle. However, if we have AVX2 and either inputs are already in place,
10305   // we will be able to shuffle even across lanes the other input in a single
10306   // instruction so skip this pattern.
10307   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10308                                  isShuffleMaskInputInPlace(1, Mask))))
10309     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10310             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10311       return Result;
10312
10313   // Otherwise fall back on generic blend lowering.
10314   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10315                                                     Mask, DAG);
10316 }
10317
10318 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10319 ///
10320 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10321 /// isn't available.
10322 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10323                                        const X86Subtarget *Subtarget,
10324                                        SelectionDAG &DAG) {
10325   SDLoc DL(Op);
10326   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10327   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10328   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10329   ArrayRef<int> Mask = SVOp->getMask();
10330   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10331
10332   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10333                                                 Subtarget, DAG))
10334     return Blend;
10335
10336   // Check for being able to broadcast a single element.
10337   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
10338                                                         Mask, Subtarget, DAG))
10339     return Broadcast;
10340
10341   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10342   // options to efficiently lower the shuffle.
10343   SmallVector<int, 4> RepeatedMask;
10344   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10345     assert(RepeatedMask.size() == 4 &&
10346            "Repeated masks must be half the mask width!");
10347     if (isSingleInputShuffleMask(Mask))
10348       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10349                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10350
10351     // Use dedicated unpack instructions for masks that match their pattern.
10352     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10353       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10354     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10355       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10356
10357     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10358     // have already handled any direct blends. We also need to squash the
10359     // repeated mask into a simulated v4f32 mask.
10360     for (int i = 0; i < 4; ++i)
10361       if (RepeatedMask[i] >= 8)
10362         RepeatedMask[i] -= 4;
10363     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10364   }
10365
10366   // If we have a single input shuffle with different shuffle patterns in the
10367   // two 128-bit lanes use the variable mask to VPERMILPS.
10368   if (isSingleInputShuffleMask(Mask)) {
10369     SDValue VPermMask[8];
10370     for (int i = 0; i < 8; ++i)
10371       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10372                                  : DAG.getConstant(Mask[i], MVT::i32);
10373     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10374       return DAG.getNode(
10375           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10376           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10377
10378     if (Subtarget->hasAVX2())
10379       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
10380                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
10381                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
10382                                                  MVT::v8i32, VPermMask)),
10383                          V1);
10384
10385     // Otherwise, fall back.
10386     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10387                                                    DAG);
10388   }
10389
10390   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10391   // shuffle.
10392   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10393           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10394     return Result;
10395
10396   // If we have AVX2 then we always want to lower with a blend because at v8 we
10397   // can fully permute the elements.
10398   if (Subtarget->hasAVX2())
10399     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10400                                                       Mask, DAG);
10401
10402   // Otherwise fall back on generic lowering.
10403   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10404 }
10405
10406 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10407 ///
10408 /// This routine is only called when we have AVX2 and thus a reasonable
10409 /// instruction set for v8i32 shuffling..
10410 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10411                                        const X86Subtarget *Subtarget,
10412                                        SelectionDAG &DAG) {
10413   SDLoc DL(Op);
10414   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10415   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10416   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10417   ArrayRef<int> Mask = SVOp->getMask();
10418   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10419   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10420
10421   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10422                                                 Subtarget, DAG))
10423     return Blend;
10424
10425   // Check for being able to broadcast a single element.
10426   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
10427                                                         Mask, Subtarget, DAG))
10428     return Broadcast;
10429
10430   // If the shuffle mask is repeated in each 128-bit lane we can use more
10431   // efficient instructions that mirror the shuffles across the two 128-bit
10432   // lanes.
10433   SmallVector<int, 4> RepeatedMask;
10434   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10435     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10436     if (isSingleInputShuffleMask(Mask))
10437       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10438                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10439
10440     // Use dedicated unpack instructions for masks that match their pattern.
10441     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10442       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10443     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10444       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10445   }
10446
10447   // If the shuffle patterns aren't repeated but it is a single input, directly
10448   // generate a cross-lane VPERMD instruction.
10449   if (isSingleInputShuffleMask(Mask)) {
10450     SDValue VPermMask[8];
10451     for (int i = 0; i < 8; ++i)
10452       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10453                                  : DAG.getConstant(Mask[i], MVT::i32);
10454     return DAG.getNode(
10455         X86ISD::VPERMV, DL, MVT::v8i32,
10456         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10457   }
10458
10459   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10460   // shuffle.
10461   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10462           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10463     return Result;
10464
10465   // Otherwise fall back on generic blend lowering.
10466   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10467                                                     Mask, DAG);
10468 }
10469
10470 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10471 ///
10472 /// This routine is only called when we have AVX2 and thus a reasonable
10473 /// instruction set for v16i16 shuffling..
10474 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10475                                         const X86Subtarget *Subtarget,
10476                                         SelectionDAG &DAG) {
10477   SDLoc DL(Op);
10478   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10479   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10480   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10481   ArrayRef<int> Mask = SVOp->getMask();
10482   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10483   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10484
10485   // Check for being able to broadcast a single element.
10486   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
10487                                                         Mask, Subtarget, DAG))
10488     return Broadcast;
10489
10490   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10491                                                 Subtarget, DAG))
10492     return Blend;
10493
10494   // Use dedicated unpack instructions for masks that match their pattern.
10495   if (isShuffleEquivalent(Mask,
10496                           // First 128-bit lane:
10497                           0, 16, 1, 17, 2, 18, 3, 19,
10498                           // Second 128-bit lane:
10499                           8, 24, 9, 25, 10, 26, 11, 27))
10500     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10501   if (isShuffleEquivalent(Mask,
10502                           // First 128-bit lane:
10503                           4, 20, 5, 21, 6, 22, 7, 23,
10504                           // Second 128-bit lane:
10505                           12, 28, 13, 29, 14, 30, 15, 31))
10506     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10507
10508   if (isSingleInputShuffleMask(Mask)) {
10509     // There are no generalized cross-lane shuffle operations available on i16
10510     // element types.
10511     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10512       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10513                                                      Mask, DAG);
10514
10515     SDValue PSHUFBMask[32];
10516     for (int i = 0; i < 16; ++i) {
10517       if (Mask[i] == -1) {
10518         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10519         continue;
10520       }
10521
10522       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10523       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10524       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
10525       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
10526     }
10527     return DAG.getNode(
10528         ISD::BITCAST, DL, MVT::v16i16,
10529         DAG.getNode(
10530             X86ISD::PSHUFB, DL, MVT::v32i8,
10531             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
10532             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
10533   }
10534
10535   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10536   // shuffle.
10537   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10538           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10539     return Result;
10540
10541   // Otherwise fall back on generic lowering.
10542   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10543 }
10544
10545 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10546 ///
10547 /// This routine is only called when we have AVX2 and thus a reasonable
10548 /// instruction set for v32i8 shuffling..
10549 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10550                                        const X86Subtarget *Subtarget,
10551                                        SelectionDAG &DAG) {
10552   SDLoc DL(Op);
10553   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10554   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10555   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10556   ArrayRef<int> Mask = SVOp->getMask();
10557   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10558   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10559
10560   // Check for being able to broadcast a single element.
10561   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
10562                                                         Mask, Subtarget, DAG))
10563     return Broadcast;
10564
10565   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10566                                                 Subtarget, DAG))
10567     return Blend;
10568
10569   // Use dedicated unpack instructions for masks that match their pattern.
10570   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10571   // 256-bit lanes.
10572   if (isShuffleEquivalent(
10573           Mask,
10574           // First 128-bit lane:
10575           0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10576           // Second 128-bit lane:
10577           16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55))
10578     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10579   if (isShuffleEquivalent(
10580           Mask,
10581           // First 128-bit lane:
10582           8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10583           // Second 128-bit lane:
10584           24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63))
10585     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10586
10587   if (isSingleInputShuffleMask(Mask)) {
10588     // There are no generalized cross-lane shuffle operations available on i8
10589     // element types.
10590     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10591       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10592                                                      Mask, DAG);
10593
10594     SDValue PSHUFBMask[32];
10595     for (int i = 0; i < 32; ++i)
10596       PSHUFBMask[i] =
10597           Mask[i] < 0
10598               ? DAG.getUNDEF(MVT::i8)
10599               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
10600
10601     return DAG.getNode(
10602         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10603         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10604   }
10605
10606   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10607   // shuffle.
10608   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10609           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10610     return Result;
10611
10612   // Otherwise fall back on generic lowering.
10613   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10614 }
10615
10616 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10617 ///
10618 /// This routine either breaks down the specific type of a 256-bit x86 vector
10619 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10620 /// together based on the available instructions.
10621 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10622                                         MVT VT, const X86Subtarget *Subtarget,
10623                                         SelectionDAG &DAG) {
10624   SDLoc DL(Op);
10625   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10626   ArrayRef<int> Mask = SVOp->getMask();
10627
10628   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10629   // check for those subtargets here and avoid much of the subtarget querying in
10630   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10631   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10632   // floating point types there eventually, just immediately cast everything to
10633   // a float and operate entirely in that domain.
10634   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10635     int ElementBits = VT.getScalarSizeInBits();
10636     if (ElementBits < 32)
10637       // No floating point type available, decompose into 128-bit vectors.
10638       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10639
10640     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10641                                 VT.getVectorNumElements());
10642     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10643     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10644     return DAG.getNode(ISD::BITCAST, DL, VT,
10645                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10646   }
10647
10648   switch (VT.SimpleTy) {
10649   case MVT::v4f64:
10650     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10651   case MVT::v4i64:
10652     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10653   case MVT::v8f32:
10654     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10655   case MVT::v8i32:
10656     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10657   case MVT::v16i16:
10658     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10659   case MVT::v32i8:
10660     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10661
10662   default:
10663     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10664   }
10665 }
10666
10667 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10668 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10669                                        const X86Subtarget *Subtarget,
10670                                        SelectionDAG &DAG) {
10671   SDLoc DL(Op);
10672   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10673   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10674   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10675   ArrayRef<int> Mask = SVOp->getMask();
10676   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10677
10678   // FIXME: Implement direct support for this type!
10679   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10680 }
10681
10682 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10683 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10684                                        const X86Subtarget *Subtarget,
10685                                        SelectionDAG &DAG) {
10686   SDLoc DL(Op);
10687   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10688   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10689   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10690   ArrayRef<int> Mask = SVOp->getMask();
10691   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10692
10693   // FIXME: Implement direct support for this type!
10694   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10695 }
10696
10697 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10698 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10699                                        const X86Subtarget *Subtarget,
10700                                        SelectionDAG &DAG) {
10701   SDLoc DL(Op);
10702   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10703   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10704   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10705   ArrayRef<int> Mask = SVOp->getMask();
10706   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10707
10708   // FIXME: Implement direct support for this type!
10709   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10710 }
10711
10712 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10713 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10714                                        const X86Subtarget *Subtarget,
10715                                        SelectionDAG &DAG) {
10716   SDLoc DL(Op);
10717   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10718   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10719   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10720   ArrayRef<int> Mask = SVOp->getMask();
10721   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10722
10723   // FIXME: Implement direct support for this type!
10724   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10725 }
10726
10727 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10728 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10729                                         const X86Subtarget *Subtarget,
10730                                         SelectionDAG &DAG) {
10731   SDLoc DL(Op);
10732   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10733   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10734   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10735   ArrayRef<int> Mask = SVOp->getMask();
10736   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10737   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10738
10739   // FIXME: Implement direct support for this type!
10740   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10741 }
10742
10743 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10744 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10745                                        const X86Subtarget *Subtarget,
10746                                        SelectionDAG &DAG) {
10747   SDLoc DL(Op);
10748   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10749   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10750   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10751   ArrayRef<int> Mask = SVOp->getMask();
10752   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10753   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10754
10755   // FIXME: Implement direct support for this type!
10756   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10757 }
10758
10759 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10760 ///
10761 /// This routine either breaks down the specific type of a 512-bit x86 vector
10762 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10763 /// together based on the available instructions.
10764 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10765                                         MVT VT, const X86Subtarget *Subtarget,
10766                                         SelectionDAG &DAG) {
10767   SDLoc DL(Op);
10768   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10769   ArrayRef<int> Mask = SVOp->getMask();
10770   assert(Subtarget->hasAVX512() &&
10771          "Cannot lower 512-bit vectors w/ basic ISA!");
10772
10773   // Check for being able to broadcast a single element.
10774   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
10775                                                         Mask, Subtarget, DAG))
10776     return Broadcast;
10777
10778   // Dispatch to each element type for lowering. If we don't have supprot for
10779   // specific element type shuffles at 512 bits, immediately split them and
10780   // lower them. Each lowering routine of a given type is allowed to assume that
10781   // the requisite ISA extensions for that element type are available.
10782   switch (VT.SimpleTy) {
10783   case MVT::v8f64:
10784     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10785   case MVT::v16f32:
10786     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10787   case MVT::v8i64:
10788     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10789   case MVT::v16i32:
10790     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10791   case MVT::v32i16:
10792     if (Subtarget->hasBWI())
10793       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10794     break;
10795   case MVT::v64i8:
10796     if (Subtarget->hasBWI())
10797       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10798     break;
10799
10800   default:
10801     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10802   }
10803
10804   // Otherwise fall back on splitting.
10805   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10806 }
10807
10808 /// \brief Top-level lowering for x86 vector shuffles.
10809 ///
10810 /// This handles decomposition, canonicalization, and lowering of all x86
10811 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10812 /// above in helper routines. The canonicalization attempts to widen shuffles
10813 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10814 /// s.t. only one of the two inputs needs to be tested, etc.
10815 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10816                                   SelectionDAG &DAG) {
10817   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10818   ArrayRef<int> Mask = SVOp->getMask();
10819   SDValue V1 = Op.getOperand(0);
10820   SDValue V2 = Op.getOperand(1);
10821   MVT VT = Op.getSimpleValueType();
10822   int NumElements = VT.getVectorNumElements();
10823   SDLoc dl(Op);
10824
10825   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10826
10827   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10828   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10829   if (V1IsUndef && V2IsUndef)
10830     return DAG.getUNDEF(VT);
10831
10832   // When we create a shuffle node we put the UNDEF node to second operand,
10833   // but in some cases the first operand may be transformed to UNDEF.
10834   // In this case we should just commute the node.
10835   if (V1IsUndef)
10836     return DAG.getCommutedVectorShuffle(*SVOp);
10837
10838   // Check for non-undef masks pointing at an undef vector and make the masks
10839   // undef as well. This makes it easier to match the shuffle based solely on
10840   // the mask.
10841   if (V2IsUndef)
10842     for (int M : Mask)
10843       if (M >= NumElements) {
10844         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10845         for (int &M : NewMask)
10846           if (M >= NumElements)
10847             M = -1;
10848         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10849       }
10850
10851   // Try to collapse shuffles into using a vector type with fewer elements but
10852   // wider element types. We cap this to not form integers or floating point
10853   // elements wider than 64 bits, but it might be interesting to form i128
10854   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10855   SmallVector<int, 16> WidenedMask;
10856   if (VT.getScalarSizeInBits() < 64 &&
10857       canWidenShuffleElements(Mask, WidenedMask)) {
10858     MVT NewEltVT = VT.isFloatingPoint()
10859                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10860                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10861     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10862     // Make sure that the new vector type is legal. For example, v2f64 isn't
10863     // legal on SSE1.
10864     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10865       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10866       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10867       return DAG.getNode(ISD::BITCAST, dl, VT,
10868                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10869     }
10870   }
10871
10872   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10873   for (int M : SVOp->getMask())
10874     if (M < 0)
10875       ++NumUndefElements;
10876     else if (M < NumElements)
10877       ++NumV1Elements;
10878     else
10879       ++NumV2Elements;
10880
10881   // Commute the shuffle as needed such that more elements come from V1 than
10882   // V2. This allows us to match the shuffle pattern strictly on how many
10883   // elements come from V1 without handling the symmetric cases.
10884   if (NumV2Elements > NumV1Elements)
10885     return DAG.getCommutedVectorShuffle(*SVOp);
10886
10887   // When the number of V1 and V2 elements are the same, try to minimize the
10888   // number of uses of V2 in the low half of the vector. When that is tied,
10889   // ensure that the sum of indices for V1 is equal to or lower than the sum
10890   // indices for V2. When those are equal, try to ensure that the number of odd
10891   // indices for V1 is lower than the number of odd indices for V2.
10892   if (NumV1Elements == NumV2Elements) {
10893     int LowV1Elements = 0, LowV2Elements = 0;
10894     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10895       if (M >= NumElements)
10896         ++LowV2Elements;
10897       else if (M >= 0)
10898         ++LowV1Elements;
10899     if (LowV2Elements > LowV1Elements) {
10900       return DAG.getCommutedVectorShuffle(*SVOp);
10901     } else if (LowV2Elements == LowV1Elements) {
10902       int SumV1Indices = 0, SumV2Indices = 0;
10903       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10904         if (SVOp->getMask()[i] >= NumElements)
10905           SumV2Indices += i;
10906         else if (SVOp->getMask()[i] >= 0)
10907           SumV1Indices += i;
10908       if (SumV2Indices < SumV1Indices) {
10909         return DAG.getCommutedVectorShuffle(*SVOp);
10910       } else if (SumV2Indices == SumV1Indices) {
10911         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10912         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10913           if (SVOp->getMask()[i] >= NumElements)
10914             NumV2OddIndices += i % 2;
10915           else if (SVOp->getMask()[i] >= 0)
10916             NumV1OddIndices += i % 2;
10917         if (NumV2OddIndices < NumV1OddIndices)
10918           return DAG.getCommutedVectorShuffle(*SVOp);
10919       }
10920     }
10921   }
10922
10923   // For each vector width, delegate to a specialized lowering routine.
10924   if (VT.getSizeInBits() == 128)
10925     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10926
10927   if (VT.getSizeInBits() == 256)
10928     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10929
10930   // Force AVX-512 vectors to be scalarized for now.
10931   // FIXME: Implement AVX-512 support!
10932   if (VT.getSizeInBits() == 512)
10933     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10934
10935   llvm_unreachable("Unimplemented!");
10936 }
10937
10938
10939 //===----------------------------------------------------------------------===//
10940 // Legacy vector shuffle lowering
10941 //
10942 // This code is the legacy code handling vector shuffles until the above
10943 // replaces its functionality and performance.
10944 //===----------------------------------------------------------------------===//
10945
10946 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
10947                         bool hasInt256, unsigned *MaskOut = nullptr) {
10948   MVT EltVT = VT.getVectorElementType();
10949
10950   // There is no blend with immediate in AVX-512.
10951   if (VT.is512BitVector())
10952     return false;
10953
10954   if (!hasSSE41 || EltVT == MVT::i8)
10955     return false;
10956   if (!hasInt256 && VT == MVT::v16i16)
10957     return false;
10958
10959   unsigned MaskValue = 0;
10960   unsigned NumElems = VT.getVectorNumElements();
10961   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10962   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10963   unsigned NumElemsInLane = NumElems / NumLanes;
10964
10965   // Blend for v16i16 should be symetric for the both lanes.
10966   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10967
10968     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
10969     int EltIdx = MaskVals[i];
10970
10971     if ((EltIdx < 0 || EltIdx == (int)i) &&
10972         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
10973       continue;
10974
10975     if (((unsigned)EltIdx == (i + NumElems)) &&
10976         (SndLaneEltIdx < 0 ||
10977          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
10978       MaskValue |= (1 << i);
10979     else
10980       return false;
10981   }
10982
10983   if (MaskOut)
10984     *MaskOut = MaskValue;
10985   return true;
10986 }
10987
10988 // Try to lower a shuffle node into a simple blend instruction.
10989 // This function assumes isBlendMask returns true for this
10990 // SuffleVectorSDNode
10991 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
10992                                           unsigned MaskValue,
10993                                           const X86Subtarget *Subtarget,
10994                                           SelectionDAG &DAG) {
10995   MVT VT = SVOp->getSimpleValueType(0);
10996   MVT EltVT = VT.getVectorElementType();
10997   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
10998                      Subtarget->hasInt256() && "Trying to lower a "
10999                                                "VECTOR_SHUFFLE to a Blend but "
11000                                                "with the wrong mask"));
11001   SDValue V1 = SVOp->getOperand(0);
11002   SDValue V2 = SVOp->getOperand(1);
11003   SDLoc dl(SVOp);
11004   unsigned NumElems = VT.getVectorNumElements();
11005
11006   // Convert i32 vectors to floating point if it is not AVX2.
11007   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
11008   MVT BlendVT = VT;
11009   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
11010     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
11011                                NumElems);
11012     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
11013     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
11014   }
11015
11016   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
11017                             DAG.getConstant(MaskValue, MVT::i32));
11018   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
11019 }
11020
11021 /// In vector type \p VT, return true if the element at index \p InputIdx
11022 /// falls on a different 128-bit lane than \p OutputIdx.
11023 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
11024                                      unsigned OutputIdx) {
11025   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
11026   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
11027 }
11028
11029 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
11030 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
11031 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
11032 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
11033 /// zero.
11034 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
11035                          SelectionDAG &DAG) {
11036   MVT VT = V1.getSimpleValueType();
11037   assert(VT.is128BitVector() || VT.is256BitVector());
11038
11039   MVT EltVT = VT.getVectorElementType();
11040   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
11041   unsigned NumElts = VT.getVectorNumElements();
11042
11043   SmallVector<SDValue, 32> PshufbMask;
11044   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
11045     int InputIdx = MaskVals[OutputIdx];
11046     unsigned InputByteIdx;
11047
11048     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
11049       InputByteIdx = 0x80;
11050     else {
11051       // Cross lane is not allowed.
11052       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
11053         return SDValue();
11054       InputByteIdx = InputIdx * EltSizeInBytes;
11055       // Index is an byte offset within the 128-bit lane.
11056       InputByteIdx &= 0xf;
11057     }
11058
11059     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
11060       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
11061       if (InputByteIdx != 0x80)
11062         ++InputByteIdx;
11063     }
11064   }
11065
11066   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
11067   if (ShufVT != VT)
11068     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
11069   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
11070                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
11071 }
11072
11073 // v8i16 shuffles - Prefer shuffles in the following order:
11074 // 1. [all]   pshuflw, pshufhw, optional move
11075 // 2. [ssse3] 1 x pshufb
11076 // 3. [ssse3] 2 x pshufb + 1 x por
11077 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
11078 static SDValue
11079 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
11080                          SelectionDAG &DAG) {
11081   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11082   SDValue V1 = SVOp->getOperand(0);
11083   SDValue V2 = SVOp->getOperand(1);
11084   SDLoc dl(SVOp);
11085   SmallVector<int, 8> MaskVals;
11086
11087   // Determine if more than 1 of the words in each of the low and high quadwords
11088   // of the result come from the same quadword of one of the two inputs.  Undef
11089   // mask values count as coming from any quadword, for better codegen.
11090   //
11091   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
11092   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
11093   unsigned LoQuad[] = { 0, 0, 0, 0 };
11094   unsigned HiQuad[] = { 0, 0, 0, 0 };
11095   // Indices of quads used.
11096   std::bitset<4> InputQuads;
11097   for (unsigned i = 0; i < 8; ++i) {
11098     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
11099     int EltIdx = SVOp->getMaskElt(i);
11100     MaskVals.push_back(EltIdx);
11101     if (EltIdx < 0) {
11102       ++Quad[0];
11103       ++Quad[1];
11104       ++Quad[2];
11105       ++Quad[3];
11106       continue;
11107     }
11108     ++Quad[EltIdx / 4];
11109     InputQuads.set(EltIdx / 4);
11110   }
11111
11112   int BestLoQuad = -1;
11113   unsigned MaxQuad = 1;
11114   for (unsigned i = 0; i < 4; ++i) {
11115     if (LoQuad[i] > MaxQuad) {
11116       BestLoQuad = i;
11117       MaxQuad = LoQuad[i];
11118     }
11119   }
11120
11121   int BestHiQuad = -1;
11122   MaxQuad = 1;
11123   for (unsigned i = 0; i < 4; ++i) {
11124     if (HiQuad[i] > MaxQuad) {
11125       BestHiQuad = i;
11126       MaxQuad = HiQuad[i];
11127     }
11128   }
11129
11130   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
11131   // of the two input vectors, shuffle them into one input vector so only a
11132   // single pshufb instruction is necessary. If there are more than 2 input
11133   // quads, disable the next transformation since it does not help SSSE3.
11134   bool V1Used = InputQuads[0] || InputQuads[1];
11135   bool V2Used = InputQuads[2] || InputQuads[3];
11136   if (Subtarget->hasSSSE3()) {
11137     if (InputQuads.count() == 2 && V1Used && V2Used) {
11138       BestLoQuad = InputQuads[0] ? 0 : 1;
11139       BestHiQuad = InputQuads[2] ? 2 : 3;
11140     }
11141     if (InputQuads.count() > 2) {
11142       BestLoQuad = -1;
11143       BestHiQuad = -1;
11144     }
11145   }
11146
11147   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
11148   // the shuffle mask.  If a quad is scored as -1, that means that it contains
11149   // words from all 4 input quadwords.
11150   SDValue NewV;
11151   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
11152     int MaskV[] = {
11153       BestLoQuad < 0 ? 0 : BestLoQuad,
11154       BestHiQuad < 0 ? 1 : BestHiQuad
11155     };
11156     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
11157                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
11158                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
11159     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
11160
11161     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
11162     // source words for the shuffle, to aid later transformations.
11163     bool AllWordsInNewV = true;
11164     bool InOrder[2] = { true, true };
11165     for (unsigned i = 0; i != 8; ++i) {
11166       int idx = MaskVals[i];
11167       if (idx != (int)i)
11168         InOrder[i/4] = false;
11169       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
11170         continue;
11171       AllWordsInNewV = false;
11172       break;
11173     }
11174
11175     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
11176     if (AllWordsInNewV) {
11177       for (int i = 0; i != 8; ++i) {
11178         int idx = MaskVals[i];
11179         if (idx < 0)
11180           continue;
11181         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
11182         if ((idx != i) && idx < 4)
11183           pshufhw = false;
11184         if ((idx != i) && idx > 3)
11185           pshuflw = false;
11186       }
11187       V1 = NewV;
11188       V2Used = false;
11189       BestLoQuad = 0;
11190       BestHiQuad = 1;
11191     }
11192
11193     // If we've eliminated the use of V2, and the new mask is a pshuflw or
11194     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
11195     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
11196       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
11197       unsigned TargetMask = 0;
11198       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
11199                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
11200       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11201       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
11202                              getShufflePSHUFLWImmediate(SVOp);
11203       V1 = NewV.getOperand(0);
11204       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
11205     }
11206   }
11207
11208   // Promote splats to a larger type which usually leads to more efficient code.
11209   // FIXME: Is this true if pshufb is available?
11210   if (SVOp->isSplat())
11211     return PromoteSplat(SVOp, DAG);
11212
11213   // If we have SSSE3, and all words of the result are from 1 input vector,
11214   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
11215   // is present, fall back to case 4.
11216   if (Subtarget->hasSSSE3()) {
11217     SmallVector<SDValue,16> pshufbMask;
11218
11219     // If we have elements from both input vectors, set the high bit of the
11220     // shuffle mask element to zero out elements that come from V2 in the V1
11221     // mask, and elements that come from V1 in the V2 mask, so that the two
11222     // results can be OR'd together.
11223     bool TwoInputs = V1Used && V2Used;
11224     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
11225     if (!TwoInputs)
11226       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11227
11228     // Calculate the shuffle mask for the second input, shuffle it, and
11229     // OR it with the first shuffled input.
11230     CommuteVectorShuffleMask(MaskVals, 8);
11231     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
11232     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11233     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11234   }
11235
11236   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
11237   // and update MaskVals with new element order.
11238   std::bitset<8> InOrder;
11239   if (BestLoQuad >= 0) {
11240     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
11241     for (int i = 0; i != 4; ++i) {
11242       int idx = MaskVals[i];
11243       if (idx < 0) {
11244         InOrder.set(i);
11245       } else if ((idx / 4) == BestLoQuad) {
11246         MaskV[i] = idx & 3;
11247         InOrder.set(i);
11248       }
11249     }
11250     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11251                                 &MaskV[0]);
11252
11253     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11254       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11255       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
11256                                   NewV.getOperand(0),
11257                                   getShufflePSHUFLWImmediate(SVOp), DAG);
11258     }
11259   }
11260
11261   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
11262   // and update MaskVals with the new element order.
11263   if (BestHiQuad >= 0) {
11264     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
11265     for (unsigned i = 4; i != 8; ++i) {
11266       int idx = MaskVals[i];
11267       if (idx < 0) {
11268         InOrder.set(i);
11269       } else if ((idx / 4) == BestHiQuad) {
11270         MaskV[i] = (idx & 3) + 4;
11271         InOrder.set(i);
11272       }
11273     }
11274     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11275                                 &MaskV[0]);
11276
11277     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11278       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11279       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
11280                                   NewV.getOperand(0),
11281                                   getShufflePSHUFHWImmediate(SVOp), DAG);
11282     }
11283   }
11284
11285   // In case BestHi & BestLo were both -1, which means each quadword has a word
11286   // from each of the four input quadwords, calculate the InOrder bitvector now
11287   // before falling through to the insert/extract cleanup.
11288   if (BestLoQuad == -1 && BestHiQuad == -1) {
11289     NewV = V1;
11290     for (int i = 0; i != 8; ++i)
11291       if (MaskVals[i] < 0 || MaskVals[i] == i)
11292         InOrder.set(i);
11293   }
11294
11295   // The other elements are put in the right place using pextrw and pinsrw.
11296   for (unsigned i = 0; i != 8; ++i) {
11297     if (InOrder[i])
11298       continue;
11299     int EltIdx = MaskVals[i];
11300     if (EltIdx < 0)
11301       continue;
11302     SDValue ExtOp = (EltIdx < 8) ?
11303       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
11304                   DAG.getIntPtrConstant(EltIdx)) :
11305       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
11306                   DAG.getIntPtrConstant(EltIdx - 8));
11307     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
11308                        DAG.getIntPtrConstant(i));
11309   }
11310   return NewV;
11311 }
11312
11313 /// \brief v16i16 shuffles
11314 ///
11315 /// FIXME: We only support generation of a single pshufb currently.  We can
11316 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
11317 /// well (e.g 2 x pshufb + 1 x por).
11318 static SDValue
11319 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
11320   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11321   SDValue V1 = SVOp->getOperand(0);
11322   SDValue V2 = SVOp->getOperand(1);
11323   SDLoc dl(SVOp);
11324
11325   if (V2.getOpcode() != ISD::UNDEF)
11326     return SDValue();
11327
11328   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11329   return getPSHUFB(MaskVals, V1, dl, DAG);
11330 }
11331
11332 // v16i8 shuffles - Prefer shuffles in the following order:
11333 // 1. [ssse3] 1 x pshufb
11334 // 2. [ssse3] 2 x pshufb + 1 x por
11335 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
11336 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
11337                                         const X86Subtarget* Subtarget,
11338                                         SelectionDAG &DAG) {
11339   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11340   SDValue V1 = SVOp->getOperand(0);
11341   SDValue V2 = SVOp->getOperand(1);
11342   SDLoc dl(SVOp);
11343   ArrayRef<int> MaskVals = SVOp->getMask();
11344
11345   // Promote splats to a larger type which usually leads to more efficient code.
11346   // FIXME: Is this true if pshufb is available?
11347   if (SVOp->isSplat())
11348     return PromoteSplat(SVOp, DAG);
11349
11350   // If we have SSSE3, case 1 is generated when all result bytes come from
11351   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
11352   // present, fall back to case 3.
11353
11354   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
11355   if (Subtarget->hasSSSE3()) {
11356     SmallVector<SDValue,16> pshufbMask;
11357
11358     // If all result elements are from one input vector, then only translate
11359     // undef mask values to 0x80 (zero out result) in the pshufb mask.
11360     //
11361     // Otherwise, we have elements from both input vectors, and must zero out
11362     // elements that come from V2 in the first mask, and V1 in the second mask
11363     // so that we can OR them together.
11364     for (unsigned i = 0; i != 16; ++i) {
11365       int EltIdx = MaskVals[i];
11366       if (EltIdx < 0 || EltIdx >= 16)
11367         EltIdx = 0x80;
11368       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11369     }
11370     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
11371                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11372                                  MVT::v16i8, pshufbMask));
11373
11374     // As PSHUFB will zero elements with negative indices, it's safe to ignore
11375     // the 2nd operand if it's undefined or zero.
11376     if (V2.getOpcode() == ISD::UNDEF ||
11377         ISD::isBuildVectorAllZeros(V2.getNode()))
11378       return V1;
11379
11380     // Calculate the shuffle mask for the second input, shuffle it, and
11381     // OR it with the first shuffled input.
11382     pshufbMask.clear();
11383     for (unsigned i = 0; i != 16; ++i) {
11384       int EltIdx = MaskVals[i];
11385       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
11386       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11387     }
11388     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
11389                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11390                                  MVT::v16i8, pshufbMask));
11391     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11392   }
11393
11394   // No SSSE3 - Calculate in place words and then fix all out of place words
11395   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
11396   // the 16 different words that comprise the two doublequadword input vectors.
11397   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11398   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
11399   SDValue NewV = V1;
11400   for (int i = 0; i != 8; ++i) {
11401     int Elt0 = MaskVals[i*2];
11402     int Elt1 = MaskVals[i*2+1];
11403
11404     // This word of the result is all undef, skip it.
11405     if (Elt0 < 0 && Elt1 < 0)
11406       continue;
11407
11408     // This word of the result is already in the correct place, skip it.
11409     if ((Elt0 == i*2) && (Elt1 == i*2+1))
11410       continue;
11411
11412     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
11413     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
11414     SDValue InsElt;
11415
11416     // If Elt0 and Elt1 are defined, are consecutive, and can be load
11417     // using a single extract together, load it and store it.
11418     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
11419       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11420                            DAG.getIntPtrConstant(Elt1 / 2));
11421       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11422                         DAG.getIntPtrConstant(i));
11423       continue;
11424     }
11425
11426     // If Elt1 is defined, extract it from the appropriate source.  If the
11427     // source byte is not also odd, shift the extracted word left 8 bits
11428     // otherwise clear the bottom 8 bits if we need to do an or.
11429     if (Elt1 >= 0) {
11430       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11431                            DAG.getIntPtrConstant(Elt1 / 2));
11432       if ((Elt1 & 1) == 0)
11433         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
11434                              DAG.getConstant(8,
11435                                   TLI.getShiftAmountTy(InsElt.getValueType())));
11436       else if (Elt0 >= 0)
11437         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
11438                              DAG.getConstant(0xFF00, MVT::i16));
11439     }
11440     // If Elt0 is defined, extract it from the appropriate source.  If the
11441     // source byte is not also even, shift the extracted word right 8 bits. If
11442     // Elt1 was also defined, OR the extracted values together before
11443     // inserting them in the result.
11444     if (Elt0 >= 0) {
11445       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
11446                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
11447       if ((Elt0 & 1) != 0)
11448         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
11449                               DAG.getConstant(8,
11450                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
11451       else if (Elt1 >= 0)
11452         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
11453                              DAG.getConstant(0x00FF, MVT::i16));
11454       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
11455                          : InsElt0;
11456     }
11457     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11458                        DAG.getIntPtrConstant(i));
11459   }
11460   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
11461 }
11462
11463 // v32i8 shuffles - Translate to VPSHUFB if possible.
11464 static
11465 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
11466                                  const X86Subtarget *Subtarget,
11467                                  SelectionDAG &DAG) {
11468   MVT VT = SVOp->getSimpleValueType(0);
11469   SDValue V1 = SVOp->getOperand(0);
11470   SDValue V2 = SVOp->getOperand(1);
11471   SDLoc dl(SVOp);
11472   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11473
11474   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11475   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
11476   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
11477
11478   // VPSHUFB may be generated if
11479   // (1) one of input vector is undefined or zeroinitializer.
11480   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
11481   // And (2) the mask indexes don't cross the 128-bit lane.
11482   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
11483       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
11484     return SDValue();
11485
11486   if (V1IsAllZero && !V2IsAllZero) {
11487     CommuteVectorShuffleMask(MaskVals, 32);
11488     V1 = V2;
11489   }
11490   return getPSHUFB(MaskVals, V1, dl, DAG);
11491 }
11492
11493 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
11494 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
11495 /// done when every pair / quad of shuffle mask elements point to elements in
11496 /// the right sequence. e.g.
11497 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
11498 static
11499 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
11500                                  SelectionDAG &DAG) {
11501   MVT VT = SVOp->getSimpleValueType(0);
11502   SDLoc dl(SVOp);
11503   unsigned NumElems = VT.getVectorNumElements();
11504   MVT NewVT;
11505   unsigned Scale;
11506   switch (VT.SimpleTy) {
11507   default: llvm_unreachable("Unexpected!");
11508   case MVT::v2i64:
11509   case MVT::v2f64:
11510            return SDValue(SVOp, 0);
11511   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
11512   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
11513   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
11514   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
11515   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
11516   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
11517   }
11518
11519   SmallVector<int, 8> MaskVec;
11520   for (unsigned i = 0; i != NumElems; i += Scale) {
11521     int StartIdx = -1;
11522     for (unsigned j = 0; j != Scale; ++j) {
11523       int EltIdx = SVOp->getMaskElt(i+j);
11524       if (EltIdx < 0)
11525         continue;
11526       if (StartIdx < 0)
11527         StartIdx = (EltIdx / Scale);
11528       if (EltIdx != (int)(StartIdx*Scale + j))
11529         return SDValue();
11530     }
11531     MaskVec.push_back(StartIdx);
11532   }
11533
11534   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
11535   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
11536   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
11537 }
11538
11539 /// getVZextMovL - Return a zero-extending vector move low node.
11540 ///
11541 static SDValue getVZextMovL(MVT VT, MVT OpVT,
11542                             SDValue SrcOp, SelectionDAG &DAG,
11543                             const X86Subtarget *Subtarget, SDLoc dl) {
11544   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
11545     LoadSDNode *LD = nullptr;
11546     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
11547       LD = dyn_cast<LoadSDNode>(SrcOp);
11548     if (!LD) {
11549       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
11550       // instead.
11551       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
11552       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
11553           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11554           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
11555           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
11556         // PR2108
11557         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
11558         return DAG.getNode(ISD::BITCAST, dl, VT,
11559                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11560                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11561                                                    OpVT,
11562                                                    SrcOp.getOperand(0)
11563                                                           .getOperand(0))));
11564       }
11565     }
11566   }
11567
11568   return DAG.getNode(ISD::BITCAST, dl, VT,
11569                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11570                                  DAG.getNode(ISD::BITCAST, dl,
11571                                              OpVT, SrcOp)));
11572 }
11573
11574 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
11575 /// which could not be matched by any known target speficic shuffle
11576 static SDValue
11577 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11578
11579   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
11580   if (NewOp.getNode())
11581     return NewOp;
11582
11583   MVT VT = SVOp->getSimpleValueType(0);
11584
11585   unsigned NumElems = VT.getVectorNumElements();
11586   unsigned NumLaneElems = NumElems / 2;
11587
11588   SDLoc dl(SVOp);
11589   MVT EltVT = VT.getVectorElementType();
11590   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
11591   SDValue Output[2];
11592
11593   SmallVector<int, 16> Mask;
11594   for (unsigned l = 0; l < 2; ++l) {
11595     // Build a shuffle mask for the output, discovering on the fly which
11596     // input vectors to use as shuffle operands (recorded in InputUsed).
11597     // If building a suitable shuffle vector proves too hard, then bail
11598     // out with UseBuildVector set.
11599     bool UseBuildVector = false;
11600     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
11601     unsigned LaneStart = l * NumLaneElems;
11602     for (unsigned i = 0; i != NumLaneElems; ++i) {
11603       // The mask element.  This indexes into the input.
11604       int Idx = SVOp->getMaskElt(i+LaneStart);
11605       if (Idx < 0) {
11606         // the mask element does not index into any input vector.
11607         Mask.push_back(-1);
11608         continue;
11609       }
11610
11611       // The input vector this mask element indexes into.
11612       int Input = Idx / NumLaneElems;
11613
11614       // Turn the index into an offset from the start of the input vector.
11615       Idx -= Input * NumLaneElems;
11616
11617       // Find or create a shuffle vector operand to hold this input.
11618       unsigned OpNo;
11619       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
11620         if (InputUsed[OpNo] == Input)
11621           // This input vector is already an operand.
11622           break;
11623         if (InputUsed[OpNo] < 0) {
11624           // Create a new operand for this input vector.
11625           InputUsed[OpNo] = Input;
11626           break;
11627         }
11628       }
11629
11630       if (OpNo >= array_lengthof(InputUsed)) {
11631         // More than two input vectors used!  Give up on trying to create a
11632         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
11633         UseBuildVector = true;
11634         break;
11635       }
11636
11637       // Add the mask index for the new shuffle vector.
11638       Mask.push_back(Idx + OpNo * NumLaneElems);
11639     }
11640
11641     if (UseBuildVector) {
11642       SmallVector<SDValue, 16> SVOps;
11643       for (unsigned i = 0; i != NumLaneElems; ++i) {
11644         // The mask element.  This indexes into the input.
11645         int Idx = SVOp->getMaskElt(i+LaneStart);
11646         if (Idx < 0) {
11647           SVOps.push_back(DAG.getUNDEF(EltVT));
11648           continue;
11649         }
11650
11651         // The input vector this mask element indexes into.
11652         int Input = Idx / NumElems;
11653
11654         // Turn the index into an offset from the start of the input vector.
11655         Idx -= Input * NumElems;
11656
11657         // Extract the vector element by hand.
11658         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
11659                                     SVOp->getOperand(Input),
11660                                     DAG.getIntPtrConstant(Idx)));
11661       }
11662
11663       // Construct the output using a BUILD_VECTOR.
11664       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
11665     } else if (InputUsed[0] < 0) {
11666       // No input vectors were used! The result is undefined.
11667       Output[l] = DAG.getUNDEF(NVT);
11668     } else {
11669       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
11670                                         (InputUsed[0] % 2) * NumLaneElems,
11671                                         DAG, dl);
11672       // If only one input was used, use an undefined vector for the other.
11673       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
11674         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
11675                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
11676       // At least one input vector was used. Create a new shuffle vector.
11677       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
11678     }
11679
11680     Mask.clear();
11681   }
11682
11683   // Concatenate the result back
11684   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
11685 }
11686
11687 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
11688 /// 4 elements, and match them with several different shuffle types.
11689 static SDValue
11690 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11691   SDValue V1 = SVOp->getOperand(0);
11692   SDValue V2 = SVOp->getOperand(1);
11693   SDLoc dl(SVOp);
11694   MVT VT = SVOp->getSimpleValueType(0);
11695
11696   assert(VT.is128BitVector() && "Unsupported vector size");
11697
11698   std::pair<int, int> Locs[4];
11699   int Mask1[] = { -1, -1, -1, -1 };
11700   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
11701
11702   unsigned NumHi = 0;
11703   unsigned NumLo = 0;
11704   for (unsigned i = 0; i != 4; ++i) {
11705     int Idx = PermMask[i];
11706     if (Idx < 0) {
11707       Locs[i] = std::make_pair(-1, -1);
11708     } else {
11709       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
11710       if (Idx < 4) {
11711         Locs[i] = std::make_pair(0, NumLo);
11712         Mask1[NumLo] = Idx;
11713         NumLo++;
11714       } else {
11715         Locs[i] = std::make_pair(1, NumHi);
11716         if (2+NumHi < 4)
11717           Mask1[2+NumHi] = Idx;
11718         NumHi++;
11719       }
11720     }
11721   }
11722
11723   if (NumLo <= 2 && NumHi <= 2) {
11724     // If no more than two elements come from either vector. This can be
11725     // implemented with two shuffles. First shuffle gather the elements.
11726     // The second shuffle, which takes the first shuffle as both of its
11727     // vector operands, put the elements into the right order.
11728     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11729
11730     int Mask2[] = { -1, -1, -1, -1 };
11731
11732     for (unsigned i = 0; i != 4; ++i)
11733       if (Locs[i].first != -1) {
11734         unsigned Idx = (i < 2) ? 0 : 4;
11735         Idx += Locs[i].first * 2 + Locs[i].second;
11736         Mask2[i] = Idx;
11737       }
11738
11739     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
11740   }
11741
11742   if (NumLo == 3 || NumHi == 3) {
11743     // Otherwise, we must have three elements from one vector, call it X, and
11744     // one element from the other, call it Y.  First, use a shufps to build an
11745     // intermediate vector with the one element from Y and the element from X
11746     // that will be in the same half in the final destination (the indexes don't
11747     // matter). Then, use a shufps to build the final vector, taking the half
11748     // containing the element from Y from the intermediate, and the other half
11749     // from X.
11750     if (NumHi == 3) {
11751       // Normalize it so the 3 elements come from V1.
11752       CommuteVectorShuffleMask(PermMask, 4);
11753       std::swap(V1, V2);
11754     }
11755
11756     // Find the element from V2.
11757     unsigned HiIndex;
11758     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
11759       int Val = PermMask[HiIndex];
11760       if (Val < 0)
11761         continue;
11762       if (Val >= 4)
11763         break;
11764     }
11765
11766     Mask1[0] = PermMask[HiIndex];
11767     Mask1[1] = -1;
11768     Mask1[2] = PermMask[HiIndex^1];
11769     Mask1[3] = -1;
11770     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11771
11772     if (HiIndex >= 2) {
11773       Mask1[0] = PermMask[0];
11774       Mask1[1] = PermMask[1];
11775       Mask1[2] = HiIndex & 1 ? 6 : 4;
11776       Mask1[3] = HiIndex & 1 ? 4 : 6;
11777       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11778     }
11779
11780     Mask1[0] = HiIndex & 1 ? 2 : 0;
11781     Mask1[1] = HiIndex & 1 ? 0 : 2;
11782     Mask1[2] = PermMask[2];
11783     Mask1[3] = PermMask[3];
11784     if (Mask1[2] >= 0)
11785       Mask1[2] += 4;
11786     if (Mask1[3] >= 0)
11787       Mask1[3] += 4;
11788     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
11789   }
11790
11791   // Break it into (shuffle shuffle_hi, shuffle_lo).
11792   int LoMask[] = { -1, -1, -1, -1 };
11793   int HiMask[] = { -1, -1, -1, -1 };
11794
11795   int *MaskPtr = LoMask;
11796   unsigned MaskIdx = 0;
11797   unsigned LoIdx = 0;
11798   unsigned HiIdx = 2;
11799   for (unsigned i = 0; i != 4; ++i) {
11800     if (i == 2) {
11801       MaskPtr = HiMask;
11802       MaskIdx = 1;
11803       LoIdx = 0;
11804       HiIdx = 2;
11805     }
11806     int Idx = PermMask[i];
11807     if (Idx < 0) {
11808       Locs[i] = std::make_pair(-1, -1);
11809     } else if (Idx < 4) {
11810       Locs[i] = std::make_pair(MaskIdx, LoIdx);
11811       MaskPtr[LoIdx] = Idx;
11812       LoIdx++;
11813     } else {
11814       Locs[i] = std::make_pair(MaskIdx, HiIdx);
11815       MaskPtr[HiIdx] = Idx;
11816       HiIdx++;
11817     }
11818   }
11819
11820   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
11821   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
11822   int MaskOps[] = { -1, -1, -1, -1 };
11823   for (unsigned i = 0; i != 4; ++i)
11824     if (Locs[i].first != -1)
11825       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
11826   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
11827 }
11828
11829 static bool MayFoldVectorLoad(SDValue V) {
11830   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
11831     V = V.getOperand(0);
11832
11833   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
11834     V = V.getOperand(0);
11835   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
11836       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
11837     // BUILD_VECTOR (load), undef
11838     V = V.getOperand(0);
11839
11840   return MayFoldLoad(V);
11841 }
11842
11843 static
11844 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
11845   MVT VT = Op.getSimpleValueType();
11846
11847   // Canonizalize to v2f64.
11848   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
11849   return DAG.getNode(ISD::BITCAST, dl, VT,
11850                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
11851                                           V1, DAG));
11852 }
11853
11854 static
11855 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
11856                         bool HasSSE2) {
11857   SDValue V1 = Op.getOperand(0);
11858   SDValue V2 = Op.getOperand(1);
11859   MVT VT = Op.getSimpleValueType();
11860
11861   assert(VT != MVT::v2i64 && "unsupported shuffle type");
11862
11863   if (HasSSE2 && VT == MVT::v2f64)
11864     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
11865
11866   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
11867   return DAG.getNode(ISD::BITCAST, dl, VT,
11868                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
11869                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
11870                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
11871 }
11872
11873 static
11874 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
11875   SDValue V1 = Op.getOperand(0);
11876   SDValue V2 = Op.getOperand(1);
11877   MVT VT = Op.getSimpleValueType();
11878
11879   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
11880          "unsupported shuffle type");
11881
11882   if (V2.getOpcode() == ISD::UNDEF)
11883     V2 = V1;
11884
11885   // v4i32 or v4f32
11886   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
11887 }
11888
11889 static
11890 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
11891   SDValue V1 = Op.getOperand(0);
11892   SDValue V2 = Op.getOperand(1);
11893   MVT VT = Op.getSimpleValueType();
11894   unsigned NumElems = VT.getVectorNumElements();
11895
11896   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
11897   // operand of these instructions is only memory, so check if there's a
11898   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
11899   // same masks.
11900   bool CanFoldLoad = false;
11901
11902   // Trivial case, when V2 comes from a load.
11903   if (MayFoldVectorLoad(V2))
11904     CanFoldLoad = true;
11905
11906   // When V1 is a load, it can be folded later into a store in isel, example:
11907   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
11908   //    turns into:
11909   //  (MOVLPSmr addr:$src1, VR128:$src2)
11910   // So, recognize this potential and also use MOVLPS or MOVLPD
11911   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
11912     CanFoldLoad = true;
11913
11914   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11915   if (CanFoldLoad) {
11916     if (HasSSE2 && NumElems == 2)
11917       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
11918
11919     if (NumElems == 4)
11920       // If we don't care about the second element, proceed to use movss.
11921       if (SVOp->getMaskElt(1) != -1)
11922         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
11923   }
11924
11925   // movl and movlp will both match v2i64, but v2i64 is never matched by
11926   // movl earlier because we make it strict to avoid messing with the movlp load
11927   // folding logic (see the code above getMOVLP call). Match it here then,
11928   // this is horrible, but will stay like this until we move all shuffle
11929   // matching to x86 specific nodes. Note that for the 1st condition all
11930   // types are matched with movsd.
11931   if (HasSSE2) {
11932     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
11933     // as to remove this logic from here, as much as possible
11934     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
11935       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11936     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11937   }
11938
11939   assert(VT != MVT::v4i32 && "unsupported shuffle type");
11940
11941   // Invert the operand order and use SHUFPS to match it.
11942   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
11943                               getShuffleSHUFImmediate(SVOp), DAG);
11944 }
11945
11946 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
11947                                          SelectionDAG &DAG) {
11948   SDLoc dl(Load);
11949   MVT VT = Load->getSimpleValueType(0);
11950   MVT EVT = VT.getVectorElementType();
11951   SDValue Addr = Load->getOperand(1);
11952   SDValue NewAddr = DAG.getNode(
11953       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
11954       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
11955
11956   SDValue NewLoad =
11957       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
11958                   DAG.getMachineFunction().getMachineMemOperand(
11959                       Load->getMemOperand(), 0, EVT.getStoreSize()));
11960   return NewLoad;
11961 }
11962
11963 // It is only safe to call this function if isINSERTPSMask is true for
11964 // this shufflevector mask.
11965 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
11966                            SelectionDAG &DAG) {
11967   // Generate an insertps instruction when inserting an f32 from memory onto a
11968   // v4f32 or when copying a member from one v4f32 to another.
11969   // We also use it for transferring i32 from one register to another,
11970   // since it simply copies the same bits.
11971   // If we're transferring an i32 from memory to a specific element in a
11972   // register, we output a generic DAG that will match the PINSRD
11973   // instruction.
11974   MVT VT = SVOp->getSimpleValueType(0);
11975   MVT EVT = VT.getVectorElementType();
11976   SDValue V1 = SVOp->getOperand(0);
11977   SDValue V2 = SVOp->getOperand(1);
11978   auto Mask = SVOp->getMask();
11979   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
11980          "unsupported vector type for insertps/pinsrd");
11981
11982   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
11983   auto FromV2Predicate = [](const int &i) { return i >= 4; };
11984   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
11985
11986   SDValue From;
11987   SDValue To;
11988   unsigned DestIndex;
11989   if (FromV1 == 1) {
11990     From = V1;
11991     To = V2;
11992     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
11993                 Mask.begin();
11994
11995     // If we have 1 element from each vector, we have to check if we're
11996     // changing V1's element's place. If so, we're done. Otherwise, we
11997     // should assume we're changing V2's element's place and behave
11998     // accordingly.
11999     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
12000     assert(DestIndex <= INT32_MAX && "truncated destination index");
12001     if (FromV1 == FromV2 &&
12002         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
12003       From = V2;
12004       To = V1;
12005       DestIndex =
12006           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
12007     }
12008   } else {
12009     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
12010            "More than one element from V1 and from V2, or no elements from one "
12011            "of the vectors. This case should not have returned true from "
12012            "isINSERTPSMask");
12013     From = V2;
12014     To = V1;
12015     DestIndex =
12016         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
12017   }
12018
12019   // Get an index into the source vector in the range [0,4) (the mask is
12020   // in the range [0,8) because it can address V1 and V2)
12021   unsigned SrcIndex = Mask[DestIndex] % 4;
12022   if (MayFoldLoad(From)) {
12023     // Trivial case, when From comes from a load and is only used by the
12024     // shuffle. Make it use insertps from the vector that we need from that
12025     // load.
12026     SDValue NewLoad =
12027         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
12028     if (!NewLoad.getNode())
12029       return SDValue();
12030
12031     if (EVT == MVT::f32) {
12032       // Create this as a scalar to vector to match the instruction pattern.
12033       SDValue LoadScalarToVector =
12034           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
12035       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
12036       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
12037                          InsertpsMask);
12038     } else { // EVT == MVT::i32
12039       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
12040       // instruction, to match the PINSRD instruction, which loads an i32 to a
12041       // certain vector element.
12042       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
12043                          DAG.getConstant(DestIndex, MVT::i32));
12044     }
12045   }
12046
12047   // Vector-element-to-vector
12048   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
12049   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
12050 }
12051
12052 // Reduce a vector shuffle to zext.
12053 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
12054                                     SelectionDAG &DAG) {
12055   // PMOVZX is only available from SSE41.
12056   if (!Subtarget->hasSSE41())
12057     return SDValue();
12058
12059   MVT VT = Op.getSimpleValueType();
12060
12061   // Only AVX2 support 256-bit vector integer extending.
12062   if (!Subtarget->hasInt256() && VT.is256BitVector())
12063     return SDValue();
12064
12065   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12066   SDLoc DL(Op);
12067   SDValue V1 = Op.getOperand(0);
12068   SDValue V2 = Op.getOperand(1);
12069   unsigned NumElems = VT.getVectorNumElements();
12070
12071   // Extending is an unary operation and the element type of the source vector
12072   // won't be equal to or larger than i64.
12073   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
12074       VT.getVectorElementType() == MVT::i64)
12075     return SDValue();
12076
12077   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
12078   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
12079   while ((1U << Shift) < NumElems) {
12080     if (SVOp->getMaskElt(1U << Shift) == 1)
12081       break;
12082     Shift += 1;
12083     // The maximal ratio is 8, i.e. from i8 to i64.
12084     if (Shift > 3)
12085       return SDValue();
12086   }
12087
12088   // Check the shuffle mask.
12089   unsigned Mask = (1U << Shift) - 1;
12090   for (unsigned i = 0; i != NumElems; ++i) {
12091     int EltIdx = SVOp->getMaskElt(i);
12092     if ((i & Mask) != 0 && EltIdx != -1)
12093       return SDValue();
12094     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
12095       return SDValue();
12096   }
12097
12098   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
12099   MVT NeVT = MVT::getIntegerVT(NBits);
12100   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
12101
12102   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
12103     return SDValue();
12104
12105   return DAG.getNode(ISD::BITCAST, DL, VT,
12106                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
12107 }
12108
12109 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
12110                                       SelectionDAG &DAG) {
12111   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12112   MVT VT = Op.getSimpleValueType();
12113   SDLoc dl(Op);
12114   SDValue V1 = Op.getOperand(0);
12115   SDValue V2 = Op.getOperand(1);
12116
12117   if (isZeroShuffle(SVOp))
12118     return getZeroVector(VT, Subtarget, DAG, dl);
12119
12120   // Handle splat operations
12121   if (SVOp->isSplat()) {
12122     // Use vbroadcast whenever the splat comes from a foldable load
12123     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
12124     if (Broadcast.getNode())
12125       return Broadcast;
12126   }
12127
12128   // Check integer expanding shuffles.
12129   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
12130   if (NewOp.getNode())
12131     return NewOp;
12132
12133   // If the shuffle can be profitably rewritten as a narrower shuffle, then
12134   // do it!
12135   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
12136       VT == MVT::v32i8) {
12137     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12138     if (NewOp.getNode())
12139       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
12140   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
12141     // FIXME: Figure out a cleaner way to do this.
12142     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
12143       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12144       if (NewOp.getNode()) {
12145         MVT NewVT = NewOp.getSimpleValueType();
12146         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
12147                                NewVT, true, false))
12148           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
12149                               dl);
12150       }
12151     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
12152       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12153       if (NewOp.getNode()) {
12154         MVT NewVT = NewOp.getSimpleValueType();
12155         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
12156           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
12157                               dl);
12158       }
12159     }
12160   }
12161   return SDValue();
12162 }
12163
12164 SDValue
12165 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
12166   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12167   SDValue V1 = Op.getOperand(0);
12168   SDValue V2 = Op.getOperand(1);
12169   MVT VT = Op.getSimpleValueType();
12170   SDLoc dl(Op);
12171   unsigned NumElems = VT.getVectorNumElements();
12172   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
12173   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
12174   bool V1IsSplat = false;
12175   bool V2IsSplat = false;
12176   bool HasSSE2 = Subtarget->hasSSE2();
12177   bool HasFp256    = Subtarget->hasFp256();
12178   bool HasInt256   = Subtarget->hasInt256();
12179   MachineFunction &MF = DAG.getMachineFunction();
12180   bool OptForSize = MF.getFunction()->getAttributes().
12181     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
12182
12183   // Check if we should use the experimental vector shuffle lowering. If so,
12184   // delegate completely to that code path.
12185   if (ExperimentalVectorShuffleLowering)
12186     return lowerVectorShuffle(Op, Subtarget, DAG);
12187
12188   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
12189
12190   if (V1IsUndef && V2IsUndef)
12191     return DAG.getUNDEF(VT);
12192
12193   // When we create a shuffle node we put the UNDEF node to second operand,
12194   // but in some cases the first operand may be transformed to UNDEF.
12195   // In this case we should just commute the node.
12196   if (V1IsUndef)
12197     return DAG.getCommutedVectorShuffle(*SVOp);
12198
12199   // Vector shuffle lowering takes 3 steps:
12200   //
12201   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
12202   //    narrowing and commutation of operands should be handled.
12203   // 2) Matching of shuffles with known shuffle masks to x86 target specific
12204   //    shuffle nodes.
12205   // 3) Rewriting of unmatched masks into new generic shuffle operations,
12206   //    so the shuffle can be broken into other shuffles and the legalizer can
12207   //    try the lowering again.
12208   //
12209   // The general idea is that no vector_shuffle operation should be left to
12210   // be matched during isel, all of them must be converted to a target specific
12211   // node here.
12212
12213   // Normalize the input vectors. Here splats, zeroed vectors, profitable
12214   // narrowing and commutation of operands should be handled. The actual code
12215   // doesn't include all of those, work in progress...
12216   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
12217   if (NewOp.getNode())
12218     return NewOp;
12219
12220   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
12221
12222   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
12223   // unpckh_undef). Only use pshufd if speed is more important than size.
12224   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12225     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12226   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12227     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12228
12229   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
12230       V2IsUndef && MayFoldVectorLoad(V1))
12231     return getMOVDDup(Op, dl, V1, DAG);
12232
12233   if (isMOVHLPS_v_undef_Mask(M, VT))
12234     return getMOVHighToLow(Op, dl, DAG);
12235
12236   // Use to match splats
12237   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
12238       (VT == MVT::v2f64 || VT == MVT::v2i64))
12239     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12240
12241   if (isPSHUFDMask(M, VT)) {
12242     // The actual implementation will match the mask in the if above and then
12243     // during isel it can match several different instructions, not only pshufd
12244     // as its name says, sad but true, emulate the behavior for now...
12245     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
12246       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
12247
12248     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
12249
12250     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
12251       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
12252
12253     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
12254       return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1, TargetMask,
12255                                   DAG);
12256
12257     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
12258                                 TargetMask, DAG);
12259   }
12260
12261   if (isPALIGNRMask(M, VT, Subtarget))
12262     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
12263                                 getShufflePALIGNRImmediate(SVOp),
12264                                 DAG);
12265
12266   if (isVALIGNMask(M, VT, Subtarget))
12267     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
12268                                 getShuffleVALIGNImmediate(SVOp),
12269                                 DAG);
12270
12271   // Check if this can be converted into a logical shift.
12272   bool isLeft = false;
12273   unsigned ShAmt = 0;
12274   SDValue ShVal;
12275   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
12276   if (isShift && ShVal.hasOneUse()) {
12277     // If the shifted value has multiple uses, it may be cheaper to use
12278     // v_set0 + movlhps or movhlps, etc.
12279     MVT EltVT = VT.getVectorElementType();
12280     ShAmt *= EltVT.getSizeInBits();
12281     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12282   }
12283
12284   if (isMOVLMask(M, VT)) {
12285     if (ISD::isBuildVectorAllZeros(V1.getNode()))
12286       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
12287     if (!isMOVLPMask(M, VT)) {
12288       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
12289         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
12290
12291       if (VT == MVT::v4i32 || VT == MVT::v4f32)
12292         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
12293     }
12294   }
12295
12296   // FIXME: fold these into legal mask.
12297   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
12298     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
12299
12300   if (isMOVHLPSMask(M, VT))
12301     return getMOVHighToLow(Op, dl, DAG);
12302
12303   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
12304     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
12305
12306   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
12307     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
12308
12309   if (isMOVLPMask(M, VT))
12310     return getMOVLP(Op, dl, DAG, HasSSE2);
12311
12312   if (ShouldXformToMOVHLPS(M, VT) ||
12313       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
12314     return DAG.getCommutedVectorShuffle(*SVOp);
12315
12316   if (isShift) {
12317     // No better options. Use a vshldq / vsrldq.
12318     MVT EltVT = VT.getVectorElementType();
12319     ShAmt *= EltVT.getSizeInBits();
12320     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12321   }
12322
12323   bool Commuted = false;
12324   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
12325   // 1,1,1,1 -> v8i16 though.
12326   BitVector UndefElements;
12327   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
12328     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12329       V1IsSplat = true;
12330   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
12331     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12332       V2IsSplat = true;
12333
12334   // Canonicalize the splat or undef, if present, to be on the RHS.
12335   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
12336     CommuteVectorShuffleMask(M, NumElems);
12337     std::swap(V1, V2);
12338     std::swap(V1IsSplat, V2IsSplat);
12339     Commuted = true;
12340   }
12341
12342   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
12343     // Shuffling low element of v1 into undef, just return v1.
12344     if (V2IsUndef)
12345       return V1;
12346     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
12347     // the instruction selector will not match, so get a canonical MOVL with
12348     // swapped operands to undo the commute.
12349     return getMOVL(DAG, dl, VT, V2, V1);
12350   }
12351
12352   if (isUNPCKLMask(M, VT, HasInt256))
12353     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12354
12355   if (isUNPCKHMask(M, VT, HasInt256))
12356     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12357
12358   if (V2IsSplat) {
12359     // Normalize mask so all entries that point to V2 points to its first
12360     // element then try to match unpck{h|l} again. If match, return a
12361     // new vector_shuffle with the corrected mask.p
12362     SmallVector<int, 8> NewMask(M.begin(), M.end());
12363     NormalizeMask(NewMask, NumElems);
12364     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
12365       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12366     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
12367       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12368   }
12369
12370   if (Commuted) {
12371     // Commute is back and try unpck* again.
12372     // FIXME: this seems wrong.
12373     CommuteVectorShuffleMask(M, NumElems);
12374     std::swap(V1, V2);
12375     std::swap(V1IsSplat, V2IsSplat);
12376
12377     if (isUNPCKLMask(M, VT, HasInt256))
12378       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12379
12380     if (isUNPCKHMask(M, VT, HasInt256))
12381       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12382   }
12383
12384   // Normalize the node to match x86 shuffle ops if needed
12385   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
12386     return DAG.getCommutedVectorShuffle(*SVOp);
12387
12388   // The checks below are all present in isShuffleMaskLegal, but they are
12389   // inlined here right now to enable us to directly emit target specific
12390   // nodes, and remove one by one until they don't return Op anymore.
12391
12392   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
12393       SVOp->getSplatIndex() == 0 && V2IsUndef) {
12394     if (VT == MVT::v2f64 || VT == MVT::v2i64)
12395       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12396   }
12397
12398   if (isPSHUFHWMask(M, VT, HasInt256))
12399     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
12400                                 getShufflePSHUFHWImmediate(SVOp),
12401                                 DAG);
12402
12403   if (isPSHUFLWMask(M, VT, HasInt256))
12404     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
12405                                 getShufflePSHUFLWImmediate(SVOp),
12406                                 DAG);
12407
12408   unsigned MaskValue;
12409   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
12410                   &MaskValue))
12411     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
12412
12413   if (isSHUFPMask(M, VT))
12414     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
12415                                 getShuffleSHUFImmediate(SVOp), DAG);
12416
12417   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12418     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12419   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12420     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12421
12422   //===--------------------------------------------------------------------===//
12423   // Generate target specific nodes for 128 or 256-bit shuffles only
12424   // supported in the AVX instruction set.
12425   //
12426
12427   // Handle VMOVDDUPY permutations
12428   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
12429     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
12430
12431   // Handle VPERMILPS/D* permutations
12432   if (isVPERMILPMask(M, VT)) {
12433     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
12434       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
12435                                   getShuffleSHUFImmediate(SVOp), DAG);
12436     return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1,
12437                                 getShuffleSHUFImmediate(SVOp), DAG);
12438   }
12439
12440   unsigned Idx;
12441   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
12442     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
12443                               Idx*(NumElems/2), DAG, dl);
12444
12445   // Handle VPERM2F128/VPERM2I128 permutations
12446   if (isVPERM2X128Mask(M, VT, HasFp256))
12447     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
12448                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
12449
12450   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
12451     return getINSERTPS(SVOp, dl, DAG);
12452
12453   unsigned Imm8;
12454   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
12455     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
12456
12457   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
12458       VT.is512BitVector()) {
12459     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
12460     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
12461     SmallVector<SDValue, 16> permclMask;
12462     for (unsigned i = 0; i != NumElems; ++i) {
12463       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
12464     }
12465
12466     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
12467     if (V2IsUndef)
12468       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
12469       return DAG.getNode(X86ISD::VPERMV, dl, VT,
12470                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
12471     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
12472                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
12473   }
12474
12475   //===--------------------------------------------------------------------===//
12476   // Since no target specific shuffle was selected for this generic one,
12477   // lower it into other known shuffles. FIXME: this isn't true yet, but
12478   // this is the plan.
12479   //
12480
12481   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
12482   if (VT == MVT::v8i16) {
12483     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
12484     if (NewOp.getNode())
12485       return NewOp;
12486   }
12487
12488   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
12489     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
12490     if (NewOp.getNode())
12491       return NewOp;
12492   }
12493
12494   if (VT == MVT::v16i8) {
12495     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
12496     if (NewOp.getNode())
12497       return NewOp;
12498   }
12499
12500   if (VT == MVT::v32i8) {
12501     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
12502     if (NewOp.getNode())
12503       return NewOp;
12504   }
12505
12506   // Handle all 128-bit wide vectors with 4 elements, and match them with
12507   // several different shuffle types.
12508   if (NumElems == 4 && VT.is128BitVector())
12509     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
12510
12511   // Handle general 256-bit shuffles
12512   if (VT.is256BitVector())
12513     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
12514
12515   return SDValue();
12516 }
12517
12518 // This function assumes its argument is a BUILD_VECTOR of constants or
12519 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
12520 // true.
12521 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
12522                                     unsigned &MaskValue) {
12523   MaskValue = 0;
12524   unsigned NumElems = BuildVector->getNumOperands();
12525   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
12526   unsigned NumLanes = (NumElems - 1) / 8 + 1;
12527   unsigned NumElemsInLane = NumElems / NumLanes;
12528
12529   // Blend for v16i16 should be symetric for the both lanes.
12530   for (unsigned i = 0; i < NumElemsInLane; ++i) {
12531     SDValue EltCond = BuildVector->getOperand(i);
12532     SDValue SndLaneEltCond =
12533         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
12534
12535     int Lane1Cond = -1, Lane2Cond = -1;
12536     if (isa<ConstantSDNode>(EltCond))
12537       Lane1Cond = !isZero(EltCond);
12538     if (isa<ConstantSDNode>(SndLaneEltCond))
12539       Lane2Cond = !isZero(SndLaneEltCond);
12540
12541     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
12542       // Lane1Cond != 0, means we want the first argument.
12543       // Lane1Cond == 0, means we want the second argument.
12544       // The encoding of this argument is 0 for the first argument, 1
12545       // for the second. Therefore, invert the condition.
12546       MaskValue |= !Lane1Cond << i;
12547     else if (Lane1Cond < 0)
12548       MaskValue |= !Lane2Cond << i;
12549     else
12550       return false;
12551   }
12552   return true;
12553 }
12554
12555 /// \brief Try to lower a VSELECT instruction to an immediate-controlled blend
12556 /// instruction.
12557 static SDValue lowerVSELECTtoBLENDI(SDValue Op, const X86Subtarget *Subtarget,
12558                                     SelectionDAG &DAG) {
12559   SDValue Cond = Op.getOperand(0);
12560   SDValue LHS = Op.getOperand(1);
12561   SDValue RHS = Op.getOperand(2);
12562   SDLoc dl(Op);
12563   MVT VT = Op.getSimpleValueType();
12564   MVT EltVT = VT.getVectorElementType();
12565   unsigned NumElems = VT.getVectorNumElements();
12566
12567   // There is no blend with immediate in AVX-512.
12568   if (VT.is512BitVector())
12569     return SDValue();
12570
12571   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
12572     return SDValue();
12573   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
12574     return SDValue();
12575
12576   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
12577     return SDValue();
12578
12579   // Check the mask for BLEND and build the value.
12580   unsigned MaskValue = 0;
12581   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
12582     return SDValue();
12583
12584   // Convert i32 vectors to floating point if it is not AVX2.
12585   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
12586   MVT BlendVT = VT;
12587   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
12588     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
12589                                NumElems);
12590     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
12591     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
12592   }
12593
12594   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
12595                             DAG.getConstant(MaskValue, MVT::i32));
12596   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
12597 }
12598
12599 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
12600   // A vselect where all conditions and data are constants can be optimized into
12601   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
12602   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
12603       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
12604       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
12605     return SDValue();
12606
12607   SDValue BlendOp = lowerVSELECTtoBLENDI(Op, Subtarget, DAG);
12608   if (BlendOp.getNode())
12609     return BlendOp;
12610
12611   // Some types for vselect were previously set to Expand, not Legal or
12612   // Custom. Return an empty SDValue so we fall-through to Expand, after
12613   // the Custom lowering phase.
12614   MVT VT = Op.getSimpleValueType();
12615   switch (VT.SimpleTy) {
12616   default:
12617     break;
12618   case MVT::v8i16:
12619   case MVT::v16i16:
12620     if (Subtarget->hasBWI() && Subtarget->hasVLX())
12621       break;
12622     return SDValue();
12623   }
12624
12625   // We couldn't create a "Blend with immediate" node.
12626   // This node should still be legal, but we'll have to emit a blendv*
12627   // instruction.
12628   return Op;
12629 }
12630
12631 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
12632   MVT VT = Op.getSimpleValueType();
12633   SDLoc dl(Op);
12634
12635   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
12636     return SDValue();
12637
12638   if (VT.getSizeInBits() == 8) {
12639     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
12640                                   Op.getOperand(0), Op.getOperand(1));
12641     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12642                                   DAG.getValueType(VT));
12643     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12644   }
12645
12646   if (VT.getSizeInBits() == 16) {
12647     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12648     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
12649     if (Idx == 0)
12650       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12651                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12652                                      DAG.getNode(ISD::BITCAST, dl,
12653                                                  MVT::v4i32,
12654                                                  Op.getOperand(0)),
12655                                      Op.getOperand(1)));
12656     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
12657                                   Op.getOperand(0), Op.getOperand(1));
12658     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12659                                   DAG.getValueType(VT));
12660     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12661   }
12662
12663   if (VT == MVT::f32) {
12664     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
12665     // the result back to FR32 register. It's only worth matching if the
12666     // result has a single use which is a store or a bitcast to i32.  And in
12667     // the case of a store, it's not worth it if the index is a constant 0,
12668     // because a MOVSSmr can be used instead, which is smaller and faster.
12669     if (!Op.hasOneUse())
12670       return SDValue();
12671     SDNode *User = *Op.getNode()->use_begin();
12672     if ((User->getOpcode() != ISD::STORE ||
12673          (isa<ConstantSDNode>(Op.getOperand(1)) &&
12674           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
12675         (User->getOpcode() != ISD::BITCAST ||
12676          User->getValueType(0) != MVT::i32))
12677       return SDValue();
12678     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12679                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
12680                                               Op.getOperand(0)),
12681                                               Op.getOperand(1));
12682     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
12683   }
12684
12685   if (VT == MVT::i32 || VT == MVT::i64) {
12686     // ExtractPS/pextrq works with constant index.
12687     if (isa<ConstantSDNode>(Op.getOperand(1)))
12688       return Op;
12689   }
12690   return SDValue();
12691 }
12692
12693 /// Extract one bit from mask vector, like v16i1 or v8i1.
12694 /// AVX-512 feature.
12695 SDValue
12696 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
12697   SDValue Vec = Op.getOperand(0);
12698   SDLoc dl(Vec);
12699   MVT VecVT = Vec.getSimpleValueType();
12700   SDValue Idx = Op.getOperand(1);
12701   MVT EltVT = Op.getSimpleValueType();
12702
12703   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
12704
12705   // variable index can't be handled in mask registers,
12706   // extend vector to VR512
12707   if (!isa<ConstantSDNode>(Idx)) {
12708     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12709     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
12710     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
12711                               ExtVT.getVectorElementType(), Ext, Idx);
12712     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
12713   }
12714
12715   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12716   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12717   unsigned MaxSift = rc->getSize()*8 - 1;
12718   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
12719                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12720   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
12721                     DAG.getConstant(MaxSift, MVT::i8));
12722   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
12723                        DAG.getIntPtrConstant(0));
12724 }
12725
12726 SDValue
12727 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
12728                                            SelectionDAG &DAG) const {
12729   SDLoc dl(Op);
12730   SDValue Vec = Op.getOperand(0);
12731   MVT VecVT = Vec.getSimpleValueType();
12732   SDValue Idx = Op.getOperand(1);
12733
12734   if (Op.getSimpleValueType() == MVT::i1)
12735     return ExtractBitFromMaskVector(Op, DAG);
12736
12737   if (!isa<ConstantSDNode>(Idx)) {
12738     if (VecVT.is512BitVector() ||
12739         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
12740          VecVT.getVectorElementType().getSizeInBits() == 32)) {
12741
12742       MVT MaskEltVT =
12743         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
12744       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
12745                                     MaskEltVT.getSizeInBits());
12746
12747       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
12748       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
12749                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
12750                                 Idx, DAG.getConstant(0, getPointerTy()));
12751       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
12752       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
12753                         Perm, DAG.getConstant(0, getPointerTy()));
12754     }
12755     return SDValue();
12756   }
12757
12758   // If this is a 256-bit vector result, first extract the 128-bit vector and
12759   // then extract the element from the 128-bit vector.
12760   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
12761
12762     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12763     // Get the 128-bit vector.
12764     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
12765     MVT EltVT = VecVT.getVectorElementType();
12766
12767     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
12768
12769     //if (IdxVal >= NumElems/2)
12770     //  IdxVal -= NumElems/2;
12771     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
12772     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
12773                        DAG.getConstant(IdxVal, MVT::i32));
12774   }
12775
12776   assert(VecVT.is128BitVector() && "Unexpected vector length");
12777
12778   if (Subtarget->hasSSE41()) {
12779     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
12780     if (Res.getNode())
12781       return Res;
12782   }
12783
12784   MVT VT = Op.getSimpleValueType();
12785   // TODO: handle v16i8.
12786   if (VT.getSizeInBits() == 16) {
12787     SDValue Vec = Op.getOperand(0);
12788     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12789     if (Idx == 0)
12790       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12791                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12792                                      DAG.getNode(ISD::BITCAST, dl,
12793                                                  MVT::v4i32, Vec),
12794                                      Op.getOperand(1)));
12795     // Transform it so it match pextrw which produces a 32-bit result.
12796     MVT EltVT = MVT::i32;
12797     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
12798                                   Op.getOperand(0), Op.getOperand(1));
12799     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
12800                                   DAG.getValueType(VT));
12801     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12802   }
12803
12804   if (VT.getSizeInBits() == 32) {
12805     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12806     if (Idx == 0)
12807       return Op;
12808
12809     // SHUFPS the element to the lowest double word, then movss.
12810     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
12811     MVT VVT = Op.getOperand(0).getSimpleValueType();
12812     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12813                                        DAG.getUNDEF(VVT), Mask);
12814     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12815                        DAG.getIntPtrConstant(0));
12816   }
12817
12818   if (VT.getSizeInBits() == 64) {
12819     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
12820     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
12821     //        to match extract_elt for f64.
12822     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12823     if (Idx == 0)
12824       return Op;
12825
12826     // UNPCKHPD the element to the lowest double word, then movsd.
12827     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
12828     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
12829     int Mask[2] = { 1, -1 };
12830     MVT VVT = Op.getOperand(0).getSimpleValueType();
12831     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12832                                        DAG.getUNDEF(VVT), Mask);
12833     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12834                        DAG.getIntPtrConstant(0));
12835   }
12836
12837   return SDValue();
12838 }
12839
12840 /// Insert one bit to mask vector, like v16i1 or v8i1.
12841 /// AVX-512 feature.
12842 SDValue
12843 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
12844   SDLoc dl(Op);
12845   SDValue Vec = Op.getOperand(0);
12846   SDValue Elt = Op.getOperand(1);
12847   SDValue Idx = Op.getOperand(2);
12848   MVT VecVT = Vec.getSimpleValueType();
12849
12850   if (!isa<ConstantSDNode>(Idx)) {
12851     // Non constant index. Extend source and destination,
12852     // insert element and then truncate the result.
12853     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12854     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
12855     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
12856       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
12857       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
12858     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
12859   }
12860
12861   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12862   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
12863   if (Vec.getOpcode() == ISD::UNDEF)
12864     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12865                        DAG.getConstant(IdxVal, MVT::i8));
12866   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12867   unsigned MaxSift = rc->getSize()*8 - 1;
12868   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12869                     DAG.getConstant(MaxSift, MVT::i8));
12870   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
12871                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12872   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
12873 }
12874
12875 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12876                                                   SelectionDAG &DAG) const {
12877   MVT VT = Op.getSimpleValueType();
12878   MVT EltVT = VT.getVectorElementType();
12879
12880   if (EltVT == MVT::i1)
12881     return InsertBitToMaskVector(Op, DAG);
12882
12883   SDLoc dl(Op);
12884   SDValue N0 = Op.getOperand(0);
12885   SDValue N1 = Op.getOperand(1);
12886   SDValue N2 = Op.getOperand(2);
12887   if (!isa<ConstantSDNode>(N2))
12888     return SDValue();
12889   auto *N2C = cast<ConstantSDNode>(N2);
12890   unsigned IdxVal = N2C->getZExtValue();
12891
12892   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
12893   // into that, and then insert the subvector back into the result.
12894   if (VT.is256BitVector() || VT.is512BitVector()) {
12895     // Get the desired 128-bit vector half.
12896     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
12897
12898     // Insert the element into the desired half.
12899     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
12900     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
12901
12902     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
12903                     DAG.getConstant(IdxIn128, MVT::i32));
12904
12905     // Insert the changed part back to the 256-bit vector
12906     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
12907   }
12908   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
12909
12910   if (Subtarget->hasSSE41()) {
12911     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
12912       unsigned Opc;
12913       if (VT == MVT::v8i16) {
12914         Opc = X86ISD::PINSRW;
12915       } else {
12916         assert(VT == MVT::v16i8);
12917         Opc = X86ISD::PINSRB;
12918       }
12919
12920       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
12921       // argument.
12922       if (N1.getValueType() != MVT::i32)
12923         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12924       if (N2.getValueType() != MVT::i32)
12925         N2 = DAG.getIntPtrConstant(IdxVal);
12926       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
12927     }
12928
12929     if (EltVT == MVT::f32) {
12930       // Bits [7:6] of the constant are the source select.  This will always be
12931       //  zero here.  The DAG Combiner may combine an extract_elt index into
12932       //  these
12933       //  bits.  For example (insert (extract, 3), 2) could be matched by
12934       //  putting
12935       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
12936       // Bits [5:4] of the constant are the destination select.  This is the
12937       //  value of the incoming immediate.
12938       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
12939       //   combine either bitwise AND or insert of float 0.0 to set these bits.
12940       N2 = DAG.getIntPtrConstant(IdxVal << 4);
12941       // Create this as a scalar to vector..
12942       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
12943       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
12944     }
12945
12946     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
12947       // PINSR* works with constant index.
12948       return Op;
12949     }
12950   }
12951
12952   if (EltVT == MVT::i8)
12953     return SDValue();
12954
12955   if (EltVT.getSizeInBits() == 16) {
12956     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12957     // as its second argument.
12958     if (N1.getValueType() != MVT::i32)
12959       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12960     if (N2.getValueType() != MVT::i32)
12961       N2 = DAG.getIntPtrConstant(IdxVal);
12962     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12963   }
12964   return SDValue();
12965 }
12966
12967 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12968   SDLoc dl(Op);
12969   MVT OpVT = Op.getSimpleValueType();
12970
12971   // If this is a 256-bit vector result, first insert into a 128-bit
12972   // vector and then insert into the 256-bit vector.
12973   if (!OpVT.is128BitVector()) {
12974     // Insert into a 128-bit vector.
12975     unsigned SizeFactor = OpVT.getSizeInBits()/128;
12976     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12977                                  OpVT.getVectorNumElements() / SizeFactor);
12978
12979     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12980
12981     // Insert the 128-bit vector.
12982     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12983   }
12984
12985   if (OpVT == MVT::v1i64 &&
12986       Op.getOperand(0).getValueType() == MVT::i64)
12987     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12988
12989   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12990   assert(OpVT.is128BitVector() && "Expected an SSE type!");
12991   return DAG.getNode(ISD::BITCAST, dl, OpVT,
12992                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
12993 }
12994
12995 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12996 // a simple subregister reference or explicit instructions to grab
12997 // upper bits of a vector.
12998 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12999                                       SelectionDAG &DAG) {
13000   SDLoc dl(Op);
13001   SDValue In =  Op.getOperand(0);
13002   SDValue Idx = Op.getOperand(1);
13003   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13004   MVT ResVT   = Op.getSimpleValueType();
13005   MVT InVT    = In.getSimpleValueType();
13006
13007   if (Subtarget->hasFp256()) {
13008     if (ResVT.is128BitVector() &&
13009         (InVT.is256BitVector() || InVT.is512BitVector()) &&
13010         isa<ConstantSDNode>(Idx)) {
13011       return Extract128BitVector(In, IdxVal, DAG, dl);
13012     }
13013     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
13014         isa<ConstantSDNode>(Idx)) {
13015       return Extract256BitVector(In, IdxVal, DAG, dl);
13016     }
13017   }
13018   return SDValue();
13019 }
13020
13021 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
13022 // simple superregister reference or explicit instructions to insert
13023 // the upper bits of a vector.
13024 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
13025                                      SelectionDAG &DAG) {
13026   if (Subtarget->hasFp256()) {
13027     SDLoc dl(Op.getNode());
13028     SDValue Vec = Op.getNode()->getOperand(0);
13029     SDValue SubVec = Op.getNode()->getOperand(1);
13030     SDValue Idx = Op.getNode()->getOperand(2);
13031
13032     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
13033          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
13034         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
13035         isa<ConstantSDNode>(Idx)) {
13036       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13037       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
13038     }
13039
13040     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
13041         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
13042         isa<ConstantSDNode>(Idx)) {
13043       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13044       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
13045     }
13046   }
13047   return SDValue();
13048 }
13049
13050 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
13051 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
13052 // one of the above mentioned nodes. It has to be wrapped because otherwise
13053 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
13054 // be used to form addressing mode. These wrapped nodes will be selected
13055 // into MOV32ri.
13056 SDValue
13057 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
13058   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
13059
13060   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13061   // global base reg.
13062   unsigned char OpFlag = 0;
13063   unsigned WrapperKind = X86ISD::Wrapper;
13064   CodeModel::Model M = DAG.getTarget().getCodeModel();
13065
13066   if (Subtarget->isPICStyleRIPRel() &&
13067       (M == CodeModel::Small || M == CodeModel::Kernel))
13068     WrapperKind = X86ISD::WrapperRIP;
13069   else if (Subtarget->isPICStyleGOT())
13070     OpFlag = X86II::MO_GOTOFF;
13071   else if (Subtarget->isPICStyleStubPIC())
13072     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13073
13074   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
13075                                              CP->getAlignment(),
13076                                              CP->getOffset(), OpFlag);
13077   SDLoc DL(CP);
13078   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13079   // With PIC, the address is actually $g + Offset.
13080   if (OpFlag) {
13081     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13082                          DAG.getNode(X86ISD::GlobalBaseReg,
13083                                      SDLoc(), getPointerTy()),
13084                          Result);
13085   }
13086
13087   return Result;
13088 }
13089
13090 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
13091   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
13092
13093   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13094   // global base reg.
13095   unsigned char OpFlag = 0;
13096   unsigned WrapperKind = X86ISD::Wrapper;
13097   CodeModel::Model M = DAG.getTarget().getCodeModel();
13098
13099   if (Subtarget->isPICStyleRIPRel() &&
13100       (M == CodeModel::Small || M == CodeModel::Kernel))
13101     WrapperKind = X86ISD::WrapperRIP;
13102   else if (Subtarget->isPICStyleGOT())
13103     OpFlag = X86II::MO_GOTOFF;
13104   else if (Subtarget->isPICStyleStubPIC())
13105     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13106
13107   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
13108                                           OpFlag);
13109   SDLoc DL(JT);
13110   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13111
13112   // With PIC, the address is actually $g + Offset.
13113   if (OpFlag)
13114     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13115                          DAG.getNode(X86ISD::GlobalBaseReg,
13116                                      SDLoc(), getPointerTy()),
13117                          Result);
13118
13119   return Result;
13120 }
13121
13122 SDValue
13123 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
13124   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13125
13126   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13127   // global base reg.
13128   unsigned char OpFlag = 0;
13129   unsigned WrapperKind = X86ISD::Wrapper;
13130   CodeModel::Model M = DAG.getTarget().getCodeModel();
13131
13132   if (Subtarget->isPICStyleRIPRel() &&
13133       (M == CodeModel::Small || M == CodeModel::Kernel)) {
13134     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
13135       OpFlag = X86II::MO_GOTPCREL;
13136     WrapperKind = X86ISD::WrapperRIP;
13137   } else if (Subtarget->isPICStyleGOT()) {
13138     OpFlag = X86II::MO_GOT;
13139   } else if (Subtarget->isPICStyleStubPIC()) {
13140     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
13141   } else if (Subtarget->isPICStyleStubNoDynamic()) {
13142     OpFlag = X86II::MO_DARWIN_NONLAZY;
13143   }
13144
13145   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
13146
13147   SDLoc DL(Op);
13148   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13149
13150   // With PIC, the address is actually $g + Offset.
13151   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
13152       !Subtarget->is64Bit()) {
13153     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13154                          DAG.getNode(X86ISD::GlobalBaseReg,
13155                                      SDLoc(), getPointerTy()),
13156                          Result);
13157   }
13158
13159   // For symbols that require a load from a stub to get the address, emit the
13160   // load.
13161   if (isGlobalStubReference(OpFlag))
13162     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
13163                          MachinePointerInfo::getGOT(), false, false, false, 0);
13164
13165   return Result;
13166 }
13167
13168 SDValue
13169 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
13170   // Create the TargetBlockAddressAddress node.
13171   unsigned char OpFlags =
13172     Subtarget->ClassifyBlockAddressReference();
13173   CodeModel::Model M = DAG.getTarget().getCodeModel();
13174   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
13175   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
13176   SDLoc dl(Op);
13177   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
13178                                              OpFlags);
13179
13180   if (Subtarget->isPICStyleRIPRel() &&
13181       (M == CodeModel::Small || M == CodeModel::Kernel))
13182     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13183   else
13184     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13185
13186   // With PIC, the address is actually $g + Offset.
13187   if (isGlobalRelativeToPICBase(OpFlags)) {
13188     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13189                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13190                          Result);
13191   }
13192
13193   return Result;
13194 }
13195
13196 SDValue
13197 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
13198                                       int64_t Offset, SelectionDAG &DAG) const {
13199   // Create the TargetGlobalAddress node, folding in the constant
13200   // offset if it is legal.
13201   unsigned char OpFlags =
13202       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
13203   CodeModel::Model M = DAG.getTarget().getCodeModel();
13204   SDValue Result;
13205   if (OpFlags == X86II::MO_NO_FLAG &&
13206       X86::isOffsetSuitableForCodeModel(Offset, M)) {
13207     // A direct static reference to a global.
13208     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
13209     Offset = 0;
13210   } else {
13211     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
13212   }
13213
13214   if (Subtarget->isPICStyleRIPRel() &&
13215       (M == CodeModel::Small || M == CodeModel::Kernel))
13216     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13217   else
13218     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13219
13220   // With PIC, the address is actually $g + Offset.
13221   if (isGlobalRelativeToPICBase(OpFlags)) {
13222     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13223                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13224                          Result);
13225   }
13226
13227   // For globals that require a load from a stub to get the address, emit the
13228   // load.
13229   if (isGlobalStubReference(OpFlags))
13230     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
13231                          MachinePointerInfo::getGOT(), false, false, false, 0);
13232
13233   // If there was a non-zero offset that we didn't fold, create an explicit
13234   // addition for it.
13235   if (Offset != 0)
13236     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
13237                          DAG.getConstant(Offset, getPointerTy()));
13238
13239   return Result;
13240 }
13241
13242 SDValue
13243 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
13244   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
13245   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
13246   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
13247 }
13248
13249 static SDValue
13250 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
13251            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
13252            unsigned char OperandFlags, bool LocalDynamic = false) {
13253   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13254   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13255   SDLoc dl(GA);
13256   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13257                                            GA->getValueType(0),
13258                                            GA->getOffset(),
13259                                            OperandFlags);
13260
13261   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
13262                                            : X86ISD::TLSADDR;
13263
13264   if (InFlag) {
13265     SDValue Ops[] = { Chain,  TGA, *InFlag };
13266     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13267   } else {
13268     SDValue Ops[]  = { Chain, TGA };
13269     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13270   }
13271
13272   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
13273   MFI->setAdjustsStack(true);
13274   MFI->setHasCalls(true);
13275
13276   SDValue Flag = Chain.getValue(1);
13277   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
13278 }
13279
13280 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
13281 static SDValue
13282 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13283                                 const EVT PtrVT) {
13284   SDValue InFlag;
13285   SDLoc dl(GA);  // ? function entry point might be better
13286   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13287                                    DAG.getNode(X86ISD::GlobalBaseReg,
13288                                                SDLoc(), PtrVT), InFlag);
13289   InFlag = Chain.getValue(1);
13290
13291   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
13292 }
13293
13294 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
13295 static SDValue
13296 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13297                                 const EVT PtrVT) {
13298   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
13299                     X86::RAX, X86II::MO_TLSGD);
13300 }
13301
13302 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
13303                                            SelectionDAG &DAG,
13304                                            const EVT PtrVT,
13305                                            bool is64Bit) {
13306   SDLoc dl(GA);
13307
13308   // Get the start address of the TLS block for this module.
13309   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
13310       .getInfo<X86MachineFunctionInfo>();
13311   MFI->incNumLocalDynamicTLSAccesses();
13312
13313   SDValue Base;
13314   if (is64Bit) {
13315     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
13316                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
13317   } else {
13318     SDValue InFlag;
13319     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13320         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
13321     InFlag = Chain.getValue(1);
13322     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
13323                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
13324   }
13325
13326   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
13327   // of Base.
13328
13329   // Build x@dtpoff.
13330   unsigned char OperandFlags = X86II::MO_DTPOFF;
13331   unsigned WrapperKind = X86ISD::Wrapper;
13332   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13333                                            GA->getValueType(0),
13334                                            GA->getOffset(), OperandFlags);
13335   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13336
13337   // Add x@dtpoff with the base.
13338   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
13339 }
13340
13341 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
13342 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13343                                    const EVT PtrVT, TLSModel::Model model,
13344                                    bool is64Bit, bool isPIC) {
13345   SDLoc dl(GA);
13346
13347   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
13348   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
13349                                                          is64Bit ? 257 : 256));
13350
13351   SDValue ThreadPointer =
13352       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
13353                   MachinePointerInfo(Ptr), false, false, false, 0);
13354
13355   unsigned char OperandFlags = 0;
13356   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
13357   // initialexec.
13358   unsigned WrapperKind = X86ISD::Wrapper;
13359   if (model == TLSModel::LocalExec) {
13360     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
13361   } else if (model == TLSModel::InitialExec) {
13362     if (is64Bit) {
13363       OperandFlags = X86II::MO_GOTTPOFF;
13364       WrapperKind = X86ISD::WrapperRIP;
13365     } else {
13366       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
13367     }
13368   } else {
13369     llvm_unreachable("Unexpected model");
13370   }
13371
13372   // emit "addl x@ntpoff,%eax" (local exec)
13373   // or "addl x@indntpoff,%eax" (initial exec)
13374   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
13375   SDValue TGA =
13376       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
13377                                  GA->getOffset(), OperandFlags);
13378   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13379
13380   if (model == TLSModel::InitialExec) {
13381     if (isPIC && !is64Bit) {
13382       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
13383                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
13384                            Offset);
13385     }
13386
13387     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
13388                          MachinePointerInfo::getGOT(), false, false, false, 0);
13389   }
13390
13391   // The address of the thread local variable is the add of the thread
13392   // pointer with the offset of the variable.
13393   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
13394 }
13395
13396 SDValue
13397 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
13398
13399   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
13400   const GlobalValue *GV = GA->getGlobal();
13401
13402   if (Subtarget->isTargetELF()) {
13403     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
13404
13405     switch (model) {
13406       case TLSModel::GeneralDynamic:
13407         if (Subtarget->is64Bit())
13408           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
13409         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
13410       case TLSModel::LocalDynamic:
13411         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
13412                                            Subtarget->is64Bit());
13413       case TLSModel::InitialExec:
13414       case TLSModel::LocalExec:
13415         return LowerToTLSExecModel(
13416             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
13417             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
13418     }
13419     llvm_unreachable("Unknown TLS model.");
13420   }
13421
13422   if (Subtarget->isTargetDarwin()) {
13423     // Darwin only has one model of TLS.  Lower to that.
13424     unsigned char OpFlag = 0;
13425     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
13426                            X86ISD::WrapperRIP : X86ISD::Wrapper;
13427
13428     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13429     // global base reg.
13430     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
13431                  !Subtarget->is64Bit();
13432     if (PIC32)
13433       OpFlag = X86II::MO_TLVP_PIC_BASE;
13434     else
13435       OpFlag = X86II::MO_TLVP;
13436     SDLoc DL(Op);
13437     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
13438                                                 GA->getValueType(0),
13439                                                 GA->getOffset(), OpFlag);
13440     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13441
13442     // With PIC32, the address is actually $g + Offset.
13443     if (PIC32)
13444       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13445                            DAG.getNode(X86ISD::GlobalBaseReg,
13446                                        SDLoc(), getPointerTy()),
13447                            Offset);
13448
13449     // Lowering the machine isd will make sure everything is in the right
13450     // location.
13451     SDValue Chain = DAG.getEntryNode();
13452     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13453     SDValue Args[] = { Chain, Offset };
13454     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
13455
13456     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
13457     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13458     MFI->setAdjustsStack(true);
13459
13460     // And our return value (tls address) is in the standard call return value
13461     // location.
13462     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13463     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
13464                               Chain.getValue(1));
13465   }
13466
13467   if (Subtarget->isTargetKnownWindowsMSVC() ||
13468       Subtarget->isTargetWindowsGNU()) {
13469     // Just use the implicit TLS architecture
13470     // Need to generate someting similar to:
13471     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
13472     //                                  ; from TEB
13473     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
13474     //   mov     rcx, qword [rdx+rcx*8]
13475     //   mov     eax, .tls$:tlsvar
13476     //   [rax+rcx] contains the address
13477     // Windows 64bit: gs:0x58
13478     // Windows 32bit: fs:__tls_array
13479
13480     SDLoc dl(GA);
13481     SDValue Chain = DAG.getEntryNode();
13482
13483     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
13484     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
13485     // use its literal value of 0x2C.
13486     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
13487                                         ? Type::getInt8PtrTy(*DAG.getContext(),
13488                                                              256)
13489                                         : Type::getInt32PtrTy(*DAG.getContext(),
13490                                                               257));
13491
13492     SDValue TlsArray =
13493         Subtarget->is64Bit()
13494             ? DAG.getIntPtrConstant(0x58)
13495             : (Subtarget->isTargetWindowsGNU()
13496                    ? DAG.getIntPtrConstant(0x2C)
13497                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
13498
13499     SDValue ThreadPointer =
13500         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
13501                     MachinePointerInfo(Ptr), false, false, false, 0);
13502
13503     // Load the _tls_index variable
13504     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
13505     if (Subtarget->is64Bit())
13506       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
13507                            IDX, MachinePointerInfo(), MVT::i32,
13508                            false, false, false, 0);
13509     else
13510       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
13511                         false, false, false, 0);
13512
13513     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
13514                                     getPointerTy());
13515     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
13516
13517     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
13518     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
13519                       false, false, false, 0);
13520
13521     // Get the offset of start of .tls section
13522     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13523                                              GA->getValueType(0),
13524                                              GA->getOffset(), X86II::MO_SECREL);
13525     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
13526
13527     // The address of the thread local variable is the add of the thread
13528     // pointer with the offset of the variable.
13529     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
13530   }
13531
13532   llvm_unreachable("TLS not implemented for this target.");
13533 }
13534
13535 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
13536 /// and take a 2 x i32 value to shift plus a shift amount.
13537 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
13538   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
13539   MVT VT = Op.getSimpleValueType();
13540   unsigned VTBits = VT.getSizeInBits();
13541   SDLoc dl(Op);
13542   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
13543   SDValue ShOpLo = Op.getOperand(0);
13544   SDValue ShOpHi = Op.getOperand(1);
13545   SDValue ShAmt  = Op.getOperand(2);
13546   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
13547   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
13548   // during isel.
13549   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13550                                   DAG.getConstant(VTBits - 1, MVT::i8));
13551   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
13552                                      DAG.getConstant(VTBits - 1, MVT::i8))
13553                        : DAG.getConstant(0, VT);
13554
13555   SDValue Tmp2, Tmp3;
13556   if (Op.getOpcode() == ISD::SHL_PARTS) {
13557     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
13558     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
13559   } else {
13560     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
13561     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
13562   }
13563
13564   // If the shift amount is larger or equal than the width of a part we can't
13565   // rely on the results of shld/shrd. Insert a test and select the appropriate
13566   // values for large shift amounts.
13567   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13568                                 DAG.getConstant(VTBits, MVT::i8));
13569   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13570                              AndNode, DAG.getConstant(0, MVT::i8));
13571
13572   SDValue Hi, Lo;
13573   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13574   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
13575   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
13576
13577   if (Op.getOpcode() == ISD::SHL_PARTS) {
13578     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13579     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13580   } else {
13581     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13582     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13583   }
13584
13585   SDValue Ops[2] = { Lo, Hi };
13586   return DAG.getMergeValues(Ops, dl);
13587 }
13588
13589 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
13590                                            SelectionDAG &DAG) const {
13591   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13592   SDLoc dl(Op);
13593
13594   if (SrcVT.isVector()) {
13595     if (SrcVT.getVectorElementType() == MVT::i1) {
13596       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
13597       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13598                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
13599                                      Op.getOperand(0)));
13600     }
13601     return SDValue();
13602   }
13603
13604   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
13605          "Unknown SINT_TO_FP to lower!");
13606
13607   // These are really Legal; return the operand so the caller accepts it as
13608   // Legal.
13609   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
13610     return Op;
13611   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
13612       Subtarget->is64Bit()) {
13613     return Op;
13614   }
13615
13616   unsigned Size = SrcVT.getSizeInBits()/8;
13617   MachineFunction &MF = DAG.getMachineFunction();
13618   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
13619   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13620   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13621                                StackSlot,
13622                                MachinePointerInfo::getFixedStack(SSFI),
13623                                false, false, 0);
13624   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
13625 }
13626
13627 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
13628                                      SDValue StackSlot,
13629                                      SelectionDAG &DAG) const {
13630   // Build the FILD
13631   SDLoc DL(Op);
13632   SDVTList Tys;
13633   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
13634   if (useSSE)
13635     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
13636   else
13637     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
13638
13639   unsigned ByteSize = SrcVT.getSizeInBits()/8;
13640
13641   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
13642   MachineMemOperand *MMO;
13643   if (FI) {
13644     int SSFI = FI->getIndex();
13645     MMO =
13646       DAG.getMachineFunction()
13647       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13648                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
13649   } else {
13650     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
13651     StackSlot = StackSlot.getOperand(1);
13652   }
13653   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
13654   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
13655                                            X86ISD::FILD, DL,
13656                                            Tys, Ops, SrcVT, MMO);
13657
13658   if (useSSE) {
13659     Chain = Result.getValue(1);
13660     SDValue InFlag = Result.getValue(2);
13661
13662     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
13663     // shouldn't be necessary except that RFP cannot be live across
13664     // multiple blocks. When stackifier is fixed, they can be uncoupled.
13665     MachineFunction &MF = DAG.getMachineFunction();
13666     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
13667     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
13668     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13669     Tys = DAG.getVTList(MVT::Other);
13670     SDValue Ops[] = {
13671       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
13672     };
13673     MachineMemOperand *MMO =
13674       DAG.getMachineFunction()
13675       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13676                             MachineMemOperand::MOStore, SSFISize, SSFISize);
13677
13678     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
13679                                     Ops, Op.getValueType(), MMO);
13680     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
13681                          MachinePointerInfo::getFixedStack(SSFI),
13682                          false, false, false, 0);
13683   }
13684
13685   return Result;
13686 }
13687
13688 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
13689 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
13690                                                SelectionDAG &DAG) const {
13691   // This algorithm is not obvious. Here it is what we're trying to output:
13692   /*
13693      movq       %rax,  %xmm0
13694      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
13695      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
13696      #ifdef __SSE3__
13697        haddpd   %xmm0, %xmm0
13698      #else
13699        pshufd   $0x4e, %xmm0, %xmm1
13700        addpd    %xmm1, %xmm0
13701      #endif
13702   */
13703
13704   SDLoc dl(Op);
13705   LLVMContext *Context = DAG.getContext();
13706
13707   // Build some magic constants.
13708   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
13709   Constant *C0 = ConstantDataVector::get(*Context, CV0);
13710   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
13711
13712   SmallVector<Constant*,2> CV1;
13713   CV1.push_back(
13714     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13715                                       APInt(64, 0x4330000000000000ULL))));
13716   CV1.push_back(
13717     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13718                                       APInt(64, 0x4530000000000000ULL))));
13719   Constant *C1 = ConstantVector::get(CV1);
13720   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
13721
13722   // Load the 64-bit value into an XMM register.
13723   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
13724                             Op.getOperand(0));
13725   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
13726                               MachinePointerInfo::getConstantPool(),
13727                               false, false, false, 16);
13728   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
13729                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
13730                               CLod0);
13731
13732   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
13733                               MachinePointerInfo::getConstantPool(),
13734                               false, false, false, 16);
13735   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
13736   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
13737   SDValue Result;
13738
13739   if (Subtarget->hasSSE3()) {
13740     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
13741     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
13742   } else {
13743     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
13744     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
13745                                            S2F, 0x4E, DAG);
13746     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
13747                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
13748                          Sub);
13749   }
13750
13751   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
13752                      DAG.getIntPtrConstant(0));
13753 }
13754
13755 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
13756 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
13757                                                SelectionDAG &DAG) const {
13758   SDLoc dl(Op);
13759   // FP constant to bias correct the final result.
13760   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13761                                    MVT::f64);
13762
13763   // Load the 32-bit value into an XMM register.
13764   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
13765                              Op.getOperand(0));
13766
13767   // Zero out the upper parts of the register.
13768   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
13769
13770   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13771                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
13772                      DAG.getIntPtrConstant(0));
13773
13774   // Or the load with the bias.
13775   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
13776                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13777                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13778                                                    MVT::v2f64, Load)),
13779                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13780                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13781                                                    MVT::v2f64, Bias)));
13782   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13783                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
13784                    DAG.getIntPtrConstant(0));
13785
13786   // Subtract the bias.
13787   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
13788
13789   // Handle final rounding.
13790   EVT DestVT = Op.getValueType();
13791
13792   if (DestVT.bitsLT(MVT::f64))
13793     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
13794                        DAG.getIntPtrConstant(0));
13795   if (DestVT.bitsGT(MVT::f64))
13796     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
13797
13798   // Handle final rounding.
13799   return Sub;
13800 }
13801
13802 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
13803                                      const X86Subtarget &Subtarget) {
13804   // The algorithm is the following:
13805   // #ifdef __SSE4_1__
13806   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13807   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13808   //                                 (uint4) 0x53000000, 0xaa);
13809   // #else
13810   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13811   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13812   // #endif
13813   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13814   //     return (float4) lo + fhi;
13815
13816   SDLoc DL(Op);
13817   SDValue V = Op->getOperand(0);
13818   EVT VecIntVT = V.getValueType();
13819   bool Is128 = VecIntVT == MVT::v4i32;
13820   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
13821   // If we convert to something else than the supported type, e.g., to v4f64,
13822   // abort early.
13823   if (VecFloatVT != Op->getValueType(0))
13824     return SDValue();
13825
13826   unsigned NumElts = VecIntVT.getVectorNumElements();
13827   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
13828          "Unsupported custom type");
13829   assert(NumElts <= 8 && "The size of the constant array must be fixed");
13830
13831   // In the #idef/#else code, we have in common:
13832   // - The vector of constants:
13833   // -- 0x4b000000
13834   // -- 0x53000000
13835   // - A shift:
13836   // -- v >> 16
13837
13838   // Create the splat vector for 0x4b000000.
13839   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
13840   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
13841                            CstLow, CstLow, CstLow, CstLow};
13842   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13843                                   makeArrayRef(&CstLowArray[0], NumElts));
13844   // Create the splat vector for 0x53000000.
13845   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
13846   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
13847                             CstHigh, CstHigh, CstHigh, CstHigh};
13848   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13849                                    makeArrayRef(&CstHighArray[0], NumElts));
13850
13851   // Create the right shift.
13852   SDValue CstShift = DAG.getConstant(16, MVT::i32);
13853   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
13854                              CstShift, CstShift, CstShift, CstShift};
13855   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13856                                     makeArrayRef(&CstShiftArray[0], NumElts));
13857   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
13858
13859   SDValue Low, High;
13860   if (Subtarget.hasSSE41()) {
13861     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
13862     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13863     SDValue VecCstLowBitcast =
13864         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
13865     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
13866     // Low will be bitcasted right away, so do not bother bitcasting back to its
13867     // original type.
13868     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
13869                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
13870     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13871     //                                 (uint4) 0x53000000, 0xaa);
13872     SDValue VecCstHighBitcast =
13873         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
13874     SDValue VecShiftBitcast =
13875         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
13876     // High will be bitcasted right away, so do not bother bitcasting back to
13877     // its original type.
13878     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
13879                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
13880   } else {
13881     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
13882     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13883                                      CstMask, CstMask, CstMask);
13884     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13885     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13886     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13887
13888     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13889     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13890   }
13891
13892   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13893   SDValue CstFAdd = DAG.getConstantFP(
13894       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
13895   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13896                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13897   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13898                                    makeArrayRef(&CstFAddArray[0], NumElts));
13899
13900   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13901   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
13902   SDValue FHigh =
13903       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13904   //     return (float4) lo + fhi;
13905   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
13906   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13907 }
13908
13909 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13910                                                SelectionDAG &DAG) const {
13911   SDValue N0 = Op.getOperand(0);
13912   MVT SVT = N0.getSimpleValueType();
13913   SDLoc dl(Op);
13914
13915   switch (SVT.SimpleTy) {
13916   default:
13917     llvm_unreachable("Custom UINT_TO_FP is not supported!");
13918   case MVT::v4i8:
13919   case MVT::v4i16:
13920   case MVT::v8i8:
13921   case MVT::v8i16: {
13922     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13923     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13924                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13925   }
13926   case MVT::v4i32:
13927   case MVT::v8i32:
13928     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13929   }
13930   llvm_unreachable(nullptr);
13931 }
13932
13933 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13934                                            SelectionDAG &DAG) const {
13935   SDValue N0 = Op.getOperand(0);
13936   SDLoc dl(Op);
13937
13938   if (Op.getValueType().isVector())
13939     return lowerUINT_TO_FP_vec(Op, DAG);
13940
13941   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13942   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13943   // the optimization here.
13944   if (DAG.SignBitIsZero(N0))
13945     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13946
13947   MVT SrcVT = N0.getSimpleValueType();
13948   MVT DstVT = Op.getSimpleValueType();
13949   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13950     return LowerUINT_TO_FP_i64(Op, DAG);
13951   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13952     return LowerUINT_TO_FP_i32(Op, DAG);
13953   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13954     return SDValue();
13955
13956   // Make a 64-bit buffer, and use it to build an FILD.
13957   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13958   if (SrcVT == MVT::i32) {
13959     SDValue WordOff = DAG.getConstant(4, getPointerTy());
13960     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
13961                                      getPointerTy(), StackSlot, WordOff);
13962     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13963                                   StackSlot, MachinePointerInfo(),
13964                                   false, false, 0);
13965     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
13966                                   OffsetSlot, MachinePointerInfo(),
13967                                   false, false, 0);
13968     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13969     return Fild;
13970   }
13971
13972   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13973   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13974                                StackSlot, MachinePointerInfo(),
13975                                false, false, 0);
13976   // For i64 source, we need to add the appropriate power of 2 if the input
13977   // was negative.  This is the same as the optimization in
13978   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13979   // we must be careful to do the computation in x87 extended precision, not
13980   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13981   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13982   MachineMemOperand *MMO =
13983     DAG.getMachineFunction()
13984     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13985                           MachineMemOperand::MOLoad, 8, 8);
13986
13987   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13988   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13989   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13990                                          MVT::i64, MMO);
13991
13992   APInt FF(32, 0x5F800000ULL);
13993
13994   // Check whether the sign bit is set.
13995   SDValue SignSet = DAG.getSetCC(dl,
13996                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
13997                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
13998                                  ISD::SETLT);
13999
14000   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
14001   SDValue FudgePtr = DAG.getConstantPool(
14002                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
14003                                          getPointerTy());
14004
14005   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
14006   SDValue Zero = DAG.getIntPtrConstant(0);
14007   SDValue Four = DAG.getIntPtrConstant(4);
14008   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
14009                                Zero, Four);
14010   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
14011
14012   // Load the value out, extending it from f32 to f80.
14013   // FIXME: Avoid the extend by constructing the right constant pool?
14014   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
14015                                  FudgePtr, MachinePointerInfo::getConstantPool(),
14016                                  MVT::f32, false, false, false, 4);
14017   // Extend everything to 80 bits to force it to be done on x87.
14018   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
14019   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
14020 }
14021
14022 std::pair<SDValue,SDValue>
14023 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
14024                                     bool IsSigned, bool IsReplace) const {
14025   SDLoc DL(Op);
14026
14027   EVT DstTy = Op.getValueType();
14028
14029   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
14030     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
14031     DstTy = MVT::i64;
14032   }
14033
14034   assert(DstTy.getSimpleVT() <= MVT::i64 &&
14035          DstTy.getSimpleVT() >= MVT::i16 &&
14036          "Unknown FP_TO_INT to lower!");
14037
14038   // These are really Legal.
14039   if (DstTy == MVT::i32 &&
14040       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14041     return std::make_pair(SDValue(), SDValue());
14042   if (Subtarget->is64Bit() &&
14043       DstTy == MVT::i64 &&
14044       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14045     return std::make_pair(SDValue(), SDValue());
14046
14047   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
14048   // stack slot, or into the FTOL runtime function.
14049   MachineFunction &MF = DAG.getMachineFunction();
14050   unsigned MemSize = DstTy.getSizeInBits()/8;
14051   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14052   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14053
14054   unsigned Opc;
14055   if (!IsSigned && isIntegerTypeFTOL(DstTy))
14056     Opc = X86ISD::WIN_FTOL;
14057   else
14058     switch (DstTy.getSimpleVT().SimpleTy) {
14059     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
14060     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
14061     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
14062     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
14063     }
14064
14065   SDValue Chain = DAG.getEntryNode();
14066   SDValue Value = Op.getOperand(0);
14067   EVT TheVT = Op.getOperand(0).getValueType();
14068   // FIXME This causes a redundant load/store if the SSE-class value is already
14069   // in memory, such as if it is on the callstack.
14070   if (isScalarFPTypeInSSEReg(TheVT)) {
14071     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
14072     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
14073                          MachinePointerInfo::getFixedStack(SSFI),
14074                          false, false, 0);
14075     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
14076     SDValue Ops[] = {
14077       Chain, StackSlot, DAG.getValueType(TheVT)
14078     };
14079
14080     MachineMemOperand *MMO =
14081       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14082                               MachineMemOperand::MOLoad, MemSize, MemSize);
14083     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
14084     Chain = Value.getValue(1);
14085     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14086     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14087   }
14088
14089   MachineMemOperand *MMO =
14090     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14091                             MachineMemOperand::MOStore, MemSize, MemSize);
14092
14093   if (Opc != X86ISD::WIN_FTOL) {
14094     // Build the FP_TO_INT*_IN_MEM
14095     SDValue Ops[] = { Chain, Value, StackSlot };
14096     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
14097                                            Ops, DstTy, MMO);
14098     return std::make_pair(FIST, StackSlot);
14099   } else {
14100     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
14101       DAG.getVTList(MVT::Other, MVT::Glue),
14102       Chain, Value);
14103     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
14104       MVT::i32, ftol.getValue(1));
14105     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
14106       MVT::i32, eax.getValue(2));
14107     SDValue Ops[] = { eax, edx };
14108     SDValue pair = IsReplace
14109       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
14110       : DAG.getMergeValues(Ops, DL);
14111     return std::make_pair(pair, SDValue());
14112   }
14113 }
14114
14115 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
14116                               const X86Subtarget *Subtarget) {
14117   MVT VT = Op->getSimpleValueType(0);
14118   SDValue In = Op->getOperand(0);
14119   MVT InVT = In.getSimpleValueType();
14120   SDLoc dl(Op);
14121
14122   // Optimize vectors in AVX mode:
14123   //
14124   //   v8i16 -> v8i32
14125   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
14126   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
14127   //   Concat upper and lower parts.
14128   //
14129   //   v4i32 -> v4i64
14130   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
14131   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
14132   //   Concat upper and lower parts.
14133   //
14134
14135   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
14136       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
14137       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
14138     return SDValue();
14139
14140   if (Subtarget->hasInt256())
14141     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
14142
14143   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
14144   SDValue Undef = DAG.getUNDEF(InVT);
14145   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
14146   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14147   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14148
14149   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
14150                              VT.getVectorNumElements()/2);
14151
14152   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14153   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14154
14155   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14156 }
14157
14158 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
14159                                         SelectionDAG &DAG) {
14160   MVT VT = Op->getSimpleValueType(0);
14161   SDValue In = Op->getOperand(0);
14162   MVT InVT = In.getSimpleValueType();
14163   SDLoc DL(Op);
14164   unsigned int NumElts = VT.getVectorNumElements();
14165   if (NumElts != 8 && NumElts != 16)
14166     return SDValue();
14167
14168   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
14169     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
14170
14171   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
14172   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14173   // Now we have only mask extension
14174   assert(InVT.getVectorElementType() == MVT::i1);
14175   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
14176   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14177   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
14178   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14179   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14180                            MachinePointerInfo::getConstantPool(),
14181                            false, false, false, Alignment);
14182
14183   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
14184   if (VT.is512BitVector())
14185     return Brcst;
14186   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
14187 }
14188
14189 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14190                                SelectionDAG &DAG) {
14191   if (Subtarget->hasFp256()) {
14192     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14193     if (Res.getNode())
14194       return Res;
14195   }
14196
14197   return SDValue();
14198 }
14199
14200 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14201                                 SelectionDAG &DAG) {
14202   SDLoc DL(Op);
14203   MVT VT = Op.getSimpleValueType();
14204   SDValue In = Op.getOperand(0);
14205   MVT SVT = In.getSimpleValueType();
14206
14207   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
14208     return LowerZERO_EXTEND_AVX512(Op, DAG);
14209
14210   if (Subtarget->hasFp256()) {
14211     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14212     if (Res.getNode())
14213       return Res;
14214   }
14215
14216   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
14217          VT.getVectorNumElements() != SVT.getVectorNumElements());
14218   return SDValue();
14219 }
14220
14221 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
14222   SDLoc DL(Op);
14223   MVT VT = Op.getSimpleValueType();
14224   SDValue In = Op.getOperand(0);
14225   MVT InVT = In.getSimpleValueType();
14226
14227   if (VT == MVT::i1) {
14228     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
14229            "Invalid scalar TRUNCATE operation");
14230     if (InVT.getSizeInBits() >= 32)
14231       return SDValue();
14232     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
14233     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
14234   }
14235   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
14236          "Invalid TRUNCATE operation");
14237
14238   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
14239     if (VT.getVectorElementType().getSizeInBits() >=8)
14240       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
14241
14242     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14243     unsigned NumElts = InVT.getVectorNumElements();
14244     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
14245     if (InVT.getSizeInBits() < 512) {
14246       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
14247       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
14248       InVT = ExtVT;
14249     }
14250
14251     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
14252     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14253     SDValue CP = DAG.getConstantPool(C, getPointerTy());
14254     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14255     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14256                            MachinePointerInfo::getConstantPool(),
14257                            false, false, false, Alignment);
14258     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
14259     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
14260     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
14261   }
14262
14263   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
14264     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
14265     if (Subtarget->hasInt256()) {
14266       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14267       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
14268       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
14269                                 ShufMask);
14270       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
14271                          DAG.getIntPtrConstant(0));
14272     }
14273
14274     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14275                                DAG.getIntPtrConstant(0));
14276     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14277                                DAG.getIntPtrConstant(2));
14278     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14279     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14280     static const int ShufMask[] = {0, 2, 4, 6};
14281     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
14282   }
14283
14284   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
14285     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
14286     if (Subtarget->hasInt256()) {
14287       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
14288
14289       SmallVector<SDValue,32> pshufbMask;
14290       for (unsigned i = 0; i < 2; ++i) {
14291         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14292         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14293         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14294         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14295         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14296         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14297         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14298         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14299         for (unsigned j = 0; j < 8; ++j)
14300           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14301       }
14302       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
14303       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
14304       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
14305
14306       static const int ShufMask[] = {0,  2,  -1,  -1};
14307       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
14308                                 &ShufMask[0]);
14309       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14310                        DAG.getIntPtrConstant(0));
14311       return DAG.getNode(ISD::BITCAST, DL, VT, In);
14312     }
14313
14314     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14315                                DAG.getIntPtrConstant(0));
14316
14317     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14318                                DAG.getIntPtrConstant(4));
14319
14320     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
14321     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
14322
14323     // The PSHUFB mask:
14324     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14325                                    -1, -1, -1, -1, -1, -1, -1, -1};
14326
14327     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14328     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
14329     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
14330
14331     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14332     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14333
14334     // The MOVLHPS Mask:
14335     static const int ShufMask2[] = {0, 1, 4, 5};
14336     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
14337     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
14338   }
14339
14340   // Handle truncation of V256 to V128 using shuffles.
14341   if (!VT.is128BitVector() || !InVT.is256BitVector())
14342     return SDValue();
14343
14344   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
14345
14346   unsigned NumElems = VT.getVectorNumElements();
14347   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
14348
14349   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
14350   // Prepare truncation shuffle mask
14351   for (unsigned i = 0; i != NumElems; ++i)
14352     MaskVec[i] = i * 2;
14353   SDValue V = DAG.getVectorShuffle(NVT, DL,
14354                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
14355                                    DAG.getUNDEF(NVT), &MaskVec[0]);
14356   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
14357                      DAG.getIntPtrConstant(0));
14358 }
14359
14360 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
14361                                            SelectionDAG &DAG) const {
14362   assert(!Op.getSimpleValueType().isVector());
14363
14364   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14365     /*IsSigned=*/ true, /*IsReplace=*/ false);
14366   SDValue FIST = Vals.first, StackSlot = Vals.second;
14367   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
14368   if (!FIST.getNode()) return Op;
14369
14370   if (StackSlot.getNode())
14371     // Load the result.
14372     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14373                        FIST, StackSlot, MachinePointerInfo(),
14374                        false, false, false, 0);
14375
14376   // The node is the result.
14377   return FIST;
14378 }
14379
14380 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
14381                                            SelectionDAG &DAG) const {
14382   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14383     /*IsSigned=*/ false, /*IsReplace=*/ false);
14384   SDValue FIST = Vals.first, StackSlot = Vals.second;
14385   assert(FIST.getNode() && "Unexpected failure");
14386
14387   if (StackSlot.getNode())
14388     // Load the result.
14389     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14390                        FIST, StackSlot, MachinePointerInfo(),
14391                        false, false, false, 0);
14392
14393   // The node is the result.
14394   return FIST;
14395 }
14396
14397 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
14398   SDLoc DL(Op);
14399   MVT VT = Op.getSimpleValueType();
14400   SDValue In = Op.getOperand(0);
14401   MVT SVT = In.getSimpleValueType();
14402
14403   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
14404
14405   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
14406                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
14407                                  In, DAG.getUNDEF(SVT)));
14408 }
14409
14410 /// The only differences between FABS and FNEG are the mask and the logic op.
14411 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
14412 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
14413   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
14414          "Wrong opcode for lowering FABS or FNEG.");
14415
14416   bool IsFABS = (Op.getOpcode() == ISD::FABS);
14417
14418   // If this is a FABS and it has an FNEG user, bail out to fold the combination
14419   // into an FNABS. We'll lower the FABS after that if it is still in use.
14420   if (IsFABS)
14421     for (SDNode *User : Op->uses())
14422       if (User->getOpcode() == ISD::FNEG)
14423         return Op;
14424
14425   SDValue Op0 = Op.getOperand(0);
14426   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
14427
14428   SDLoc dl(Op);
14429   MVT VT = Op.getSimpleValueType();
14430   // Assume scalar op for initialization; update for vector if needed.
14431   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
14432   // generate a 16-byte vector constant and logic op even for the scalar case.
14433   // Using a 16-byte mask allows folding the load of the mask with
14434   // the logic op, so it can save (~4 bytes) on code size.
14435   MVT EltVT = VT;
14436   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
14437   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
14438   // decide if we should generate a 16-byte constant mask when we only need 4 or
14439   // 8 bytes for the scalar case.
14440   if (VT.isVector()) {
14441     EltVT = VT.getVectorElementType();
14442     NumElts = VT.getVectorNumElements();
14443   }
14444
14445   unsigned EltBits = EltVT.getSizeInBits();
14446   LLVMContext *Context = DAG.getContext();
14447   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
14448   APInt MaskElt =
14449     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
14450   Constant *C = ConstantInt::get(*Context, MaskElt);
14451   C = ConstantVector::getSplat(NumElts, C);
14452   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14453   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
14454   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14455   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14456                              MachinePointerInfo::getConstantPool(),
14457                              false, false, false, Alignment);
14458
14459   if (VT.isVector()) {
14460     // For a vector, cast operands to a vector type, perform the logic op,
14461     // and cast the result back to the original value type.
14462     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
14463     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
14464     SDValue Operand = IsFNABS ?
14465       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
14466       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
14467     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
14468     return DAG.getNode(ISD::BITCAST, dl, VT,
14469                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
14470   }
14471
14472   // If not vector, then scalar.
14473   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
14474   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
14475   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
14476 }
14477
14478 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
14479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14480   LLVMContext *Context = DAG.getContext();
14481   SDValue Op0 = Op.getOperand(0);
14482   SDValue Op1 = Op.getOperand(1);
14483   SDLoc dl(Op);
14484   MVT VT = Op.getSimpleValueType();
14485   MVT SrcVT = Op1.getSimpleValueType();
14486
14487   // If second operand is smaller, extend it first.
14488   if (SrcVT.bitsLT(VT)) {
14489     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
14490     SrcVT = VT;
14491   }
14492   // And if it is bigger, shrink it first.
14493   if (SrcVT.bitsGT(VT)) {
14494     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
14495     SrcVT = VT;
14496   }
14497
14498   // At this point the operands and the result should have the same
14499   // type, and that won't be f80 since that is not custom lowered.
14500
14501   const fltSemantics &Sem =
14502       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
14503   const unsigned SizeInBits = VT.getSizeInBits();
14504
14505   SmallVector<Constant *, 4> CV(
14506       VT == MVT::f64 ? 2 : 4,
14507       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
14508
14509   // First, clear all bits but the sign bit from the second operand (sign).
14510   CV[0] = ConstantFP::get(*Context,
14511                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
14512   Constant *C = ConstantVector::get(CV);
14513   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14514   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
14515                               MachinePointerInfo::getConstantPool(),
14516                               false, false, false, 16);
14517   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
14518
14519   // Next, clear the sign bit from the first operand (magnitude).
14520   // If it's a constant, we can clear it here.
14521   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
14522     APFloat APF = Op0CN->getValueAPF();
14523     // If the magnitude is a positive zero, the sign bit alone is enough.
14524     if (APF.isPosZero())
14525       return SignBit;
14526     APF.clearSign();
14527     CV[0] = ConstantFP::get(*Context, APF);
14528   } else {
14529     CV[0] = ConstantFP::get(
14530         *Context,
14531         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
14532   }
14533   C = ConstantVector::get(CV);
14534   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14535   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14536                             MachinePointerInfo::getConstantPool(),
14537                             false, false, false, 16);
14538   // If the magnitude operand wasn't a constant, we need to AND out the sign.
14539   if (!isa<ConstantFPSDNode>(Op0))
14540     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
14541
14542   // OR the magnitude value with the sign bit.
14543   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
14544 }
14545
14546 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
14547   SDValue N0 = Op.getOperand(0);
14548   SDLoc dl(Op);
14549   MVT VT = Op.getSimpleValueType();
14550
14551   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
14552   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
14553                                   DAG.getConstant(1, VT));
14554   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
14555 }
14556
14557 // Check whether an OR'd tree is PTEST-able.
14558 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
14559                                       SelectionDAG &DAG) {
14560   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
14561
14562   if (!Subtarget->hasSSE41())
14563     return SDValue();
14564
14565   if (!Op->hasOneUse())
14566     return SDValue();
14567
14568   SDNode *N = Op.getNode();
14569   SDLoc DL(N);
14570
14571   SmallVector<SDValue, 8> Opnds;
14572   DenseMap<SDValue, unsigned> VecInMap;
14573   SmallVector<SDValue, 8> VecIns;
14574   EVT VT = MVT::Other;
14575
14576   // Recognize a special case where a vector is casted into wide integer to
14577   // test all 0s.
14578   Opnds.push_back(N->getOperand(0));
14579   Opnds.push_back(N->getOperand(1));
14580
14581   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14582     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
14583     // BFS traverse all OR'd operands.
14584     if (I->getOpcode() == ISD::OR) {
14585       Opnds.push_back(I->getOperand(0));
14586       Opnds.push_back(I->getOperand(1));
14587       // Re-evaluate the number of nodes to be traversed.
14588       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14589       continue;
14590     }
14591
14592     // Quit if a non-EXTRACT_VECTOR_ELT
14593     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14594       return SDValue();
14595
14596     // Quit if without a constant index.
14597     SDValue Idx = I->getOperand(1);
14598     if (!isa<ConstantSDNode>(Idx))
14599       return SDValue();
14600
14601     SDValue ExtractedFromVec = I->getOperand(0);
14602     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
14603     if (M == VecInMap.end()) {
14604       VT = ExtractedFromVec.getValueType();
14605       // Quit if not 128/256-bit vector.
14606       if (!VT.is128BitVector() && !VT.is256BitVector())
14607         return SDValue();
14608       // Quit if not the same type.
14609       if (VecInMap.begin() != VecInMap.end() &&
14610           VT != VecInMap.begin()->first.getValueType())
14611         return SDValue();
14612       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
14613       VecIns.push_back(ExtractedFromVec);
14614     }
14615     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14616   }
14617
14618   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14619          "Not extracted from 128-/256-bit vector.");
14620
14621   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
14622
14623   for (DenseMap<SDValue, unsigned>::const_iterator
14624         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
14625     // Quit if not all elements are used.
14626     if (I->second != FullMask)
14627       return SDValue();
14628   }
14629
14630   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
14631
14632   // Cast all vectors into TestVT for PTEST.
14633   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
14634     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
14635
14636   // If more than one full vectors are evaluated, OR them first before PTEST.
14637   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
14638     // Each iteration will OR 2 nodes and append the result until there is only
14639     // 1 node left, i.e. the final OR'd value of all vectors.
14640     SDValue LHS = VecIns[Slot];
14641     SDValue RHS = VecIns[Slot + 1];
14642     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
14643   }
14644
14645   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
14646                      VecIns.back(), VecIns.back());
14647 }
14648
14649 /// \brief return true if \c Op has a use that doesn't just read flags.
14650 static bool hasNonFlagsUse(SDValue Op) {
14651   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
14652        ++UI) {
14653     SDNode *User = *UI;
14654     unsigned UOpNo = UI.getOperandNo();
14655     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
14656       // Look pass truncate.
14657       UOpNo = User->use_begin().getOperandNo();
14658       User = *User->use_begin();
14659     }
14660
14661     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
14662         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
14663       return true;
14664   }
14665   return false;
14666 }
14667
14668 /// Emit nodes that will be selected as "test Op0,Op0", or something
14669 /// equivalent.
14670 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
14671                                     SelectionDAG &DAG) const {
14672   if (Op.getValueType() == MVT::i1)
14673     // KORTEST instruction should be selected
14674     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14675                        DAG.getConstant(0, Op.getValueType()));
14676
14677   // CF and OF aren't always set the way we want. Determine which
14678   // of these we need.
14679   bool NeedCF = false;
14680   bool NeedOF = false;
14681   switch (X86CC) {
14682   default: break;
14683   case X86::COND_A: case X86::COND_AE:
14684   case X86::COND_B: case X86::COND_BE:
14685     NeedCF = true;
14686     break;
14687   case X86::COND_G: case X86::COND_GE:
14688   case X86::COND_L: case X86::COND_LE:
14689   case X86::COND_O: case X86::COND_NO: {
14690     // Check if we really need to set the
14691     // Overflow flag. If NoSignedWrap is present
14692     // that is not actually needed.
14693     switch (Op->getOpcode()) {
14694     case ISD::ADD:
14695     case ISD::SUB:
14696     case ISD::MUL:
14697     case ISD::SHL: {
14698       const BinaryWithFlagsSDNode *BinNode =
14699           cast<BinaryWithFlagsSDNode>(Op.getNode());
14700       if (BinNode->hasNoSignedWrap())
14701         break;
14702     }
14703     default:
14704       NeedOF = true;
14705       break;
14706     }
14707     break;
14708   }
14709   }
14710   // See if we can use the EFLAGS value from the operand instead of
14711   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14712   // we prove that the arithmetic won't overflow, we can't use OF or CF.
14713   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14714     // Emit a CMP with 0, which is the TEST pattern.
14715     //if (Op.getValueType() == MVT::i1)
14716     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14717     //                     DAG.getConstant(0, MVT::i1));
14718     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14719                        DAG.getConstant(0, Op.getValueType()));
14720   }
14721   unsigned Opcode = 0;
14722   unsigned NumOperands = 0;
14723
14724   // Truncate operations may prevent the merge of the SETCC instruction
14725   // and the arithmetic instruction before it. Attempt to truncate the operands
14726   // of the arithmetic instruction and use a reduced bit-width instruction.
14727   bool NeedTruncation = false;
14728   SDValue ArithOp = Op;
14729   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14730     SDValue Arith = Op->getOperand(0);
14731     // Both the trunc and the arithmetic op need to have one user each.
14732     if (Arith->hasOneUse())
14733       switch (Arith.getOpcode()) {
14734         default: break;
14735         case ISD::ADD:
14736         case ISD::SUB:
14737         case ISD::AND:
14738         case ISD::OR:
14739         case ISD::XOR: {
14740           NeedTruncation = true;
14741           ArithOp = Arith;
14742         }
14743       }
14744   }
14745
14746   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14747   // which may be the result of a CAST.  We use the variable 'Op', which is the
14748   // non-casted variable when we check for possible users.
14749   switch (ArithOp.getOpcode()) {
14750   case ISD::ADD:
14751     // Due to an isel shortcoming, be conservative if this add is likely to be
14752     // selected as part of a load-modify-store instruction. When the root node
14753     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14754     // uses of other nodes in the match, such as the ADD in this case. This
14755     // leads to the ADD being left around and reselected, with the result being
14756     // two adds in the output.  Alas, even if none our users are stores, that
14757     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14758     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14759     // climbing the DAG back to the root, and it doesn't seem to be worth the
14760     // effort.
14761     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14762          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14763       if (UI->getOpcode() != ISD::CopyToReg &&
14764           UI->getOpcode() != ISD::SETCC &&
14765           UI->getOpcode() != ISD::STORE)
14766         goto default_case;
14767
14768     if (ConstantSDNode *C =
14769         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14770       // An add of one will be selected as an INC.
14771       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
14772         Opcode = X86ISD::INC;
14773         NumOperands = 1;
14774         break;
14775       }
14776
14777       // An add of negative one (subtract of one) will be selected as a DEC.
14778       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
14779         Opcode = X86ISD::DEC;
14780         NumOperands = 1;
14781         break;
14782       }
14783     }
14784
14785     // Otherwise use a regular EFLAGS-setting add.
14786     Opcode = X86ISD::ADD;
14787     NumOperands = 2;
14788     break;
14789   case ISD::SHL:
14790   case ISD::SRL:
14791     // If we have a constant logical shift that's only used in a comparison
14792     // against zero turn it into an equivalent AND. This allows turning it into
14793     // a TEST instruction later.
14794     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14795         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14796       EVT VT = Op.getValueType();
14797       unsigned BitWidth = VT.getSizeInBits();
14798       unsigned ShAmt = Op->getConstantOperandVal(1);
14799       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14800         break;
14801       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14802                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14803                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14804       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14805         break;
14806       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14807                                 DAG.getConstant(Mask, VT));
14808       DAG.ReplaceAllUsesWith(Op, New);
14809       Op = New;
14810     }
14811     break;
14812
14813   case ISD::AND:
14814     // If the primary and result isn't used, don't bother using X86ISD::AND,
14815     // because a TEST instruction will be better.
14816     if (!hasNonFlagsUse(Op))
14817       break;
14818     // FALL THROUGH
14819   case ISD::SUB:
14820   case ISD::OR:
14821   case ISD::XOR:
14822     // Due to the ISEL shortcoming noted above, be conservative if this op is
14823     // likely to be selected as part of a load-modify-store instruction.
14824     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14825            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14826       if (UI->getOpcode() == ISD::STORE)
14827         goto default_case;
14828
14829     // Otherwise use a regular EFLAGS-setting instruction.
14830     switch (ArithOp.getOpcode()) {
14831     default: llvm_unreachable("unexpected operator!");
14832     case ISD::SUB: Opcode = X86ISD::SUB; break;
14833     case ISD::XOR: Opcode = X86ISD::XOR; break;
14834     case ISD::AND: Opcode = X86ISD::AND; break;
14835     case ISD::OR: {
14836       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14837         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14838         if (EFLAGS.getNode())
14839           return EFLAGS;
14840       }
14841       Opcode = X86ISD::OR;
14842       break;
14843     }
14844     }
14845
14846     NumOperands = 2;
14847     break;
14848   case X86ISD::ADD:
14849   case X86ISD::SUB:
14850   case X86ISD::INC:
14851   case X86ISD::DEC:
14852   case X86ISD::OR:
14853   case X86ISD::XOR:
14854   case X86ISD::AND:
14855     return SDValue(Op.getNode(), 1);
14856   default:
14857   default_case:
14858     break;
14859   }
14860
14861   // If we found that truncation is beneficial, perform the truncation and
14862   // update 'Op'.
14863   if (NeedTruncation) {
14864     EVT VT = Op.getValueType();
14865     SDValue WideVal = Op->getOperand(0);
14866     EVT WideVT = WideVal.getValueType();
14867     unsigned ConvertedOp = 0;
14868     // Use a target machine opcode to prevent further DAGCombine
14869     // optimizations that may separate the arithmetic operations
14870     // from the setcc node.
14871     switch (WideVal.getOpcode()) {
14872       default: break;
14873       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14874       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14875       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14876       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14877       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14878     }
14879
14880     if (ConvertedOp) {
14881       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14882       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14883         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14884         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14885         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14886       }
14887     }
14888   }
14889
14890   if (Opcode == 0)
14891     // Emit a CMP with 0, which is the TEST pattern.
14892     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14893                        DAG.getConstant(0, Op.getValueType()));
14894
14895   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14896   SmallVector<SDValue, 4> Ops;
14897   for (unsigned i = 0; i != NumOperands; ++i)
14898     Ops.push_back(Op.getOperand(i));
14899
14900   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14901   DAG.ReplaceAllUsesWith(Op, New);
14902   return SDValue(New.getNode(), 1);
14903 }
14904
14905 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14906 /// equivalent.
14907 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14908                                    SDLoc dl, SelectionDAG &DAG) const {
14909   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
14910     if (C->getAPIntValue() == 0)
14911       return EmitTest(Op0, X86CC, dl, DAG);
14912
14913      if (Op0.getValueType() == MVT::i1)
14914        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
14915   }
14916
14917   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14918        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14919     // Do the comparison at i32 if it's smaller, besides the Atom case.
14920     // This avoids subregister aliasing issues. Keep the smaller reference
14921     // if we're optimizing for size, however, as that'll allow better folding
14922     // of memory operations.
14923     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14924         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
14925              AttributeSet::FunctionIndex, Attribute::MinSize) &&
14926         !Subtarget->isAtom()) {
14927       unsigned ExtendOp =
14928           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14929       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14930       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14931     }
14932     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14933     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14934     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14935                               Op0, Op1);
14936     return SDValue(Sub.getNode(), 1);
14937   }
14938   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14939 }
14940
14941 /// Convert a comparison if required by the subtarget.
14942 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14943                                                  SelectionDAG &DAG) const {
14944   // If the subtarget does not support the FUCOMI instruction, floating-point
14945   // comparisons have to be converted.
14946   if (Subtarget->hasCMov() ||
14947       Cmp.getOpcode() != X86ISD::CMP ||
14948       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14949       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14950     return Cmp;
14951
14952   // The instruction selector will select an FUCOM instruction instead of
14953   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14954   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14955   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14956   SDLoc dl(Cmp);
14957   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14958   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14959   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14960                             DAG.getConstant(8, MVT::i8));
14961   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14962   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14963 }
14964
14965 /// The minimum architected relative accuracy is 2^-12. We need one
14966 /// Newton-Raphson step to have a good float result (24 bits of precision).
14967 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14968                                             DAGCombinerInfo &DCI,
14969                                             unsigned &RefinementSteps,
14970                                             bool &UseOneConstNR) const {
14971   // FIXME: We should use instruction latency models to calculate the cost of
14972   // each potential sequence, but this is very hard to do reliably because
14973   // at least Intel's Core* chips have variable timing based on the number of
14974   // significant digits in the divisor and/or sqrt operand.
14975   if (!Subtarget->useSqrtEst())
14976     return SDValue();
14977
14978   EVT VT = Op.getValueType();
14979
14980   // SSE1 has rsqrtss and rsqrtps.
14981   // TODO: Add support for AVX512 (v16f32).
14982   // It is likely not profitable to do this for f64 because a double-precision
14983   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14984   // instructions: convert to single, rsqrtss, convert back to double, refine
14985   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14986   // along with FMA, this could be a throughput win.
14987   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14988       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14989     RefinementSteps = 1;
14990     UseOneConstNR = false;
14991     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14992   }
14993   return SDValue();
14994 }
14995
14996 /// The minimum architected relative accuracy is 2^-12. We need one
14997 /// Newton-Raphson step to have a good float result (24 bits of precision).
14998 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14999                                             DAGCombinerInfo &DCI,
15000                                             unsigned &RefinementSteps) const {
15001   // FIXME: We should use instruction latency models to calculate the cost of
15002   // each potential sequence, but this is very hard to do reliably because
15003   // at least Intel's Core* chips have variable timing based on the number of
15004   // significant digits in the divisor.
15005   if (!Subtarget->useReciprocalEst())
15006     return SDValue();
15007
15008   EVT VT = Op.getValueType();
15009
15010   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
15011   // TODO: Add support for AVX512 (v16f32).
15012   // It is likely not profitable to do this for f64 because a double-precision
15013   // reciprocal estimate with refinement on x86 prior to FMA requires
15014   // 15 instructions: convert to single, rcpss, convert back to double, refine
15015   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
15016   // along with FMA, this could be a throughput win.
15017   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
15018       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
15019     RefinementSteps = ReciprocalEstimateRefinementSteps;
15020     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
15021   }
15022   return SDValue();
15023 }
15024
15025 static bool isAllOnes(SDValue V) {
15026   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
15027   return C && C->isAllOnesValue();
15028 }
15029
15030 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
15031 /// if it's possible.
15032 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
15033                                      SDLoc dl, SelectionDAG &DAG) const {
15034   SDValue Op0 = And.getOperand(0);
15035   SDValue Op1 = And.getOperand(1);
15036   if (Op0.getOpcode() == ISD::TRUNCATE)
15037     Op0 = Op0.getOperand(0);
15038   if (Op1.getOpcode() == ISD::TRUNCATE)
15039     Op1 = Op1.getOperand(0);
15040
15041   SDValue LHS, RHS;
15042   if (Op1.getOpcode() == ISD::SHL)
15043     std::swap(Op0, Op1);
15044   if (Op0.getOpcode() == ISD::SHL) {
15045     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
15046       if (And00C->getZExtValue() == 1) {
15047         // If we looked past a truncate, check that it's only truncating away
15048         // known zeros.
15049         unsigned BitWidth = Op0.getValueSizeInBits();
15050         unsigned AndBitWidth = And.getValueSizeInBits();
15051         if (BitWidth > AndBitWidth) {
15052           APInt Zeros, Ones;
15053           DAG.computeKnownBits(Op0, Zeros, Ones);
15054           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
15055             return SDValue();
15056         }
15057         LHS = Op1;
15058         RHS = Op0.getOperand(1);
15059       }
15060   } else if (Op1.getOpcode() == ISD::Constant) {
15061     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
15062     uint64_t AndRHSVal = AndRHS->getZExtValue();
15063     SDValue AndLHS = Op0;
15064
15065     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
15066       LHS = AndLHS.getOperand(0);
15067       RHS = AndLHS.getOperand(1);
15068     }
15069
15070     // Use BT if the immediate can't be encoded in a TEST instruction.
15071     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
15072       LHS = AndLHS;
15073       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
15074     }
15075   }
15076
15077   if (LHS.getNode()) {
15078     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
15079     // instruction.  Since the shift amount is in-range-or-undefined, we know
15080     // that doing a bittest on the i32 value is ok.  We extend to i32 because
15081     // the encoding for the i16 version is larger than the i32 version.
15082     // Also promote i16 to i32 for performance / code size reason.
15083     if (LHS.getValueType() == MVT::i8 ||
15084         LHS.getValueType() == MVT::i16)
15085       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
15086
15087     // If the operand types disagree, extend the shift amount to match.  Since
15088     // BT ignores high bits (like shifts) we can use anyextend.
15089     if (LHS.getValueType() != RHS.getValueType())
15090       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
15091
15092     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
15093     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
15094     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15095                        DAG.getConstant(Cond, MVT::i8), BT);
15096   }
15097
15098   return SDValue();
15099 }
15100
15101 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
15102 /// mask CMPs.
15103 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
15104                               SDValue &Op1) {
15105   unsigned SSECC;
15106   bool Swap = false;
15107
15108   // SSE Condition code mapping:
15109   //  0 - EQ
15110   //  1 - LT
15111   //  2 - LE
15112   //  3 - UNORD
15113   //  4 - NEQ
15114   //  5 - NLT
15115   //  6 - NLE
15116   //  7 - ORD
15117   switch (SetCCOpcode) {
15118   default: llvm_unreachable("Unexpected SETCC condition");
15119   case ISD::SETOEQ:
15120   case ISD::SETEQ:  SSECC = 0; break;
15121   case ISD::SETOGT:
15122   case ISD::SETGT:  Swap = true; // Fallthrough
15123   case ISD::SETLT:
15124   case ISD::SETOLT: SSECC = 1; break;
15125   case ISD::SETOGE:
15126   case ISD::SETGE:  Swap = true; // Fallthrough
15127   case ISD::SETLE:
15128   case ISD::SETOLE: SSECC = 2; break;
15129   case ISD::SETUO:  SSECC = 3; break;
15130   case ISD::SETUNE:
15131   case ISD::SETNE:  SSECC = 4; break;
15132   case ISD::SETULE: Swap = true; // Fallthrough
15133   case ISD::SETUGE: SSECC = 5; break;
15134   case ISD::SETULT: Swap = true; // Fallthrough
15135   case ISD::SETUGT: SSECC = 6; break;
15136   case ISD::SETO:   SSECC = 7; break;
15137   case ISD::SETUEQ:
15138   case ISD::SETONE: SSECC = 8; break;
15139   }
15140   if (Swap)
15141     std::swap(Op0, Op1);
15142
15143   return SSECC;
15144 }
15145
15146 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
15147 // ones, and then concatenate the result back.
15148 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
15149   MVT VT = Op.getSimpleValueType();
15150
15151   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
15152          "Unsupported value type for operation");
15153
15154   unsigned NumElems = VT.getVectorNumElements();
15155   SDLoc dl(Op);
15156   SDValue CC = Op.getOperand(2);
15157
15158   // Extract the LHS vectors
15159   SDValue LHS = Op.getOperand(0);
15160   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15161   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15162
15163   // Extract the RHS vectors
15164   SDValue RHS = Op.getOperand(1);
15165   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15166   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15167
15168   // Issue the operation on the smaller types and concatenate the result back
15169   MVT EltVT = VT.getVectorElementType();
15170   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15171   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15172                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
15173                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
15174 }
15175
15176 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
15177                                      const X86Subtarget *Subtarget) {
15178   SDValue Op0 = Op.getOperand(0);
15179   SDValue Op1 = Op.getOperand(1);
15180   SDValue CC = Op.getOperand(2);
15181   MVT VT = Op.getSimpleValueType();
15182   SDLoc dl(Op);
15183
15184   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
15185          Op.getValueType().getScalarType() == MVT::i1 &&
15186          "Cannot set masked compare for this operation");
15187
15188   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15189   unsigned  Opc = 0;
15190   bool Unsigned = false;
15191   bool Swap = false;
15192   unsigned SSECC;
15193   switch (SetCCOpcode) {
15194   default: llvm_unreachable("Unexpected SETCC condition");
15195   case ISD::SETNE:  SSECC = 4; break;
15196   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
15197   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
15198   case ISD::SETLT:  Swap = true; //fall-through
15199   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
15200   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
15201   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
15202   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
15203   case ISD::SETULE: Unsigned = true; //fall-through
15204   case ISD::SETLE:  SSECC = 2; break;
15205   }
15206
15207   if (Swap)
15208     std::swap(Op0, Op1);
15209   if (Opc)
15210     return DAG.getNode(Opc, dl, VT, Op0, Op1);
15211   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
15212   return DAG.getNode(Opc, dl, VT, Op0, Op1,
15213                      DAG.getConstant(SSECC, MVT::i8));
15214 }
15215
15216 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
15217 /// operand \p Op1.  If non-trivial (for example because it's not constant)
15218 /// return an empty value.
15219 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
15220 {
15221   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
15222   if (!BV)
15223     return SDValue();
15224
15225   MVT VT = Op1.getSimpleValueType();
15226   MVT EVT = VT.getVectorElementType();
15227   unsigned n = VT.getVectorNumElements();
15228   SmallVector<SDValue, 8> ULTOp1;
15229
15230   for (unsigned i = 0; i < n; ++i) {
15231     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
15232     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
15233       return SDValue();
15234
15235     // Avoid underflow.
15236     APInt Val = Elt->getAPIntValue();
15237     if (Val == 0)
15238       return SDValue();
15239
15240     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
15241   }
15242
15243   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
15244 }
15245
15246 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
15247                            SelectionDAG &DAG) {
15248   SDValue Op0 = Op.getOperand(0);
15249   SDValue Op1 = Op.getOperand(1);
15250   SDValue CC = Op.getOperand(2);
15251   MVT VT = Op.getSimpleValueType();
15252   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15253   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
15254   SDLoc dl(Op);
15255
15256   if (isFP) {
15257 #ifndef NDEBUG
15258     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
15259     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
15260 #endif
15261
15262     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
15263     unsigned Opc = X86ISD::CMPP;
15264     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
15265       assert(VT.getVectorNumElements() <= 16);
15266       Opc = X86ISD::CMPM;
15267     }
15268     // In the two special cases we can't handle, emit two comparisons.
15269     if (SSECC == 8) {
15270       unsigned CC0, CC1;
15271       unsigned CombineOpc;
15272       if (SetCCOpcode == ISD::SETUEQ) {
15273         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
15274       } else {
15275         assert(SetCCOpcode == ISD::SETONE);
15276         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
15277       }
15278
15279       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15280                                  DAG.getConstant(CC0, MVT::i8));
15281       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15282                                  DAG.getConstant(CC1, MVT::i8));
15283       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
15284     }
15285     // Handle all other FP comparisons here.
15286     return DAG.getNode(Opc, dl, VT, Op0, Op1,
15287                        DAG.getConstant(SSECC, MVT::i8));
15288   }
15289
15290   // Break 256-bit integer vector compare into smaller ones.
15291   if (VT.is256BitVector() && !Subtarget->hasInt256())
15292     return Lower256IntVSETCC(Op, DAG);
15293
15294   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
15295   EVT OpVT = Op1.getValueType();
15296   if (Subtarget->hasAVX512()) {
15297     if (Op1.getValueType().is512BitVector() ||
15298         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
15299         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
15300       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
15301
15302     // In AVX-512 architecture setcc returns mask with i1 elements,
15303     // But there is no compare instruction for i8 and i16 elements in KNL.
15304     // We are not talking about 512-bit operands in this case, these
15305     // types are illegal.
15306     if (MaskResult &&
15307         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
15308          OpVT.getVectorElementType().getSizeInBits() >= 8))
15309       return DAG.getNode(ISD::TRUNCATE, dl, VT,
15310                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
15311   }
15312
15313   // We are handling one of the integer comparisons here.  Since SSE only has
15314   // GT and EQ comparisons for integer, swapping operands and multiple
15315   // operations may be required for some comparisons.
15316   unsigned Opc;
15317   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
15318   bool Subus = false;
15319
15320   switch (SetCCOpcode) {
15321   default: llvm_unreachable("Unexpected SETCC condition");
15322   case ISD::SETNE:  Invert = true;
15323   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
15324   case ISD::SETLT:  Swap = true;
15325   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
15326   case ISD::SETGE:  Swap = true;
15327   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
15328                     Invert = true; break;
15329   case ISD::SETULT: Swap = true;
15330   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
15331                     FlipSigns = true; break;
15332   case ISD::SETUGE: Swap = true;
15333   case ISD::SETULE: Opc = X86ISD::PCMPGT;
15334                     FlipSigns = true; Invert = true; break;
15335   }
15336
15337   // Special case: Use min/max operations for SETULE/SETUGE
15338   MVT VET = VT.getVectorElementType();
15339   bool hasMinMax =
15340        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
15341     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
15342
15343   if (hasMinMax) {
15344     switch (SetCCOpcode) {
15345     default: break;
15346     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
15347     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
15348     }
15349
15350     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
15351   }
15352
15353   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
15354   if (!MinMax && hasSubus) {
15355     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
15356     // Op0 u<= Op1:
15357     //   t = psubus Op0, Op1
15358     //   pcmpeq t, <0..0>
15359     switch (SetCCOpcode) {
15360     default: break;
15361     case ISD::SETULT: {
15362       // If the comparison is against a constant we can turn this into a
15363       // setule.  With psubus, setule does not require a swap.  This is
15364       // beneficial because the constant in the register is no longer
15365       // destructed as the destination so it can be hoisted out of a loop.
15366       // Only do this pre-AVX since vpcmp* is no longer destructive.
15367       if (Subtarget->hasAVX())
15368         break;
15369       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
15370       if (ULEOp1.getNode()) {
15371         Op1 = ULEOp1;
15372         Subus = true; Invert = false; Swap = false;
15373       }
15374       break;
15375     }
15376     // Psubus is better than flip-sign because it requires no inversion.
15377     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
15378     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
15379     }
15380
15381     if (Subus) {
15382       Opc = X86ISD::SUBUS;
15383       FlipSigns = false;
15384     }
15385   }
15386
15387   if (Swap)
15388     std::swap(Op0, Op1);
15389
15390   // Check that the operation in question is available (most are plain SSE2,
15391   // but PCMPGTQ and PCMPEQQ have different requirements).
15392   if (VT == MVT::v2i64) {
15393     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
15394       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
15395
15396       // First cast everything to the right type.
15397       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15398       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15399
15400       // Since SSE has no unsigned integer comparisons, we need to flip the sign
15401       // bits of the inputs before performing those operations. The lower
15402       // compare is always unsigned.
15403       SDValue SB;
15404       if (FlipSigns) {
15405         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
15406       } else {
15407         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
15408         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
15409         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
15410                          Sign, Zero, Sign, Zero);
15411       }
15412       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
15413       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
15414
15415       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
15416       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
15417       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
15418
15419       // Create masks for only the low parts/high parts of the 64 bit integers.
15420       static const int MaskHi[] = { 1, 1, 3, 3 };
15421       static const int MaskLo[] = { 0, 0, 2, 2 };
15422       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
15423       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
15424       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
15425
15426       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
15427       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
15428
15429       if (Invert)
15430         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15431
15432       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15433     }
15434
15435     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
15436       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
15437       // pcmpeqd + pshufd + pand.
15438       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
15439
15440       // First cast everything to the right type.
15441       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15442       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15443
15444       // Do the compare.
15445       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
15446
15447       // Make sure the lower and upper halves are both all-ones.
15448       static const int Mask[] = { 1, 0, 3, 2 };
15449       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
15450       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
15451
15452       if (Invert)
15453         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15454
15455       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15456     }
15457   }
15458
15459   // Since SSE has no unsigned integer comparisons, we need to flip the sign
15460   // bits of the inputs before performing those operations.
15461   if (FlipSigns) {
15462     EVT EltVT = VT.getVectorElementType();
15463     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
15464     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
15465     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
15466   }
15467
15468   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
15469
15470   // If the logical-not of the result is required, perform that now.
15471   if (Invert)
15472     Result = DAG.getNOT(dl, Result, VT);
15473
15474   if (MinMax)
15475     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
15476
15477   if (Subus)
15478     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
15479                          getZeroVector(VT, Subtarget, DAG, dl));
15480
15481   return Result;
15482 }
15483
15484 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
15485
15486   MVT VT = Op.getSimpleValueType();
15487
15488   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
15489
15490   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
15491          && "SetCC type must be 8-bit or 1-bit integer");
15492   SDValue Op0 = Op.getOperand(0);
15493   SDValue Op1 = Op.getOperand(1);
15494   SDLoc dl(Op);
15495   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
15496
15497   // Optimize to BT if possible.
15498   // Lower (X & (1 << N)) == 0 to BT(X, N).
15499   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
15500   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
15501   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
15502       Op1.getOpcode() == ISD::Constant &&
15503       cast<ConstantSDNode>(Op1)->isNullValue() &&
15504       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15505     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
15506     if (NewSetCC.getNode()) {
15507       if (VT == MVT::i1)
15508         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
15509       return NewSetCC;
15510     }
15511   }
15512
15513   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
15514   // these.
15515   if (Op1.getOpcode() == ISD::Constant &&
15516       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
15517        cast<ConstantSDNode>(Op1)->isNullValue()) &&
15518       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15519
15520     // If the input is a setcc, then reuse the input setcc or use a new one with
15521     // the inverted condition.
15522     if (Op0.getOpcode() == X86ISD::SETCC) {
15523       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
15524       bool Invert = (CC == ISD::SETNE) ^
15525         cast<ConstantSDNode>(Op1)->isNullValue();
15526       if (!Invert)
15527         return Op0;
15528
15529       CCode = X86::GetOppositeBranchCondition(CCode);
15530       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15531                                   DAG.getConstant(CCode, MVT::i8),
15532                                   Op0.getOperand(1));
15533       if (VT == MVT::i1)
15534         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15535       return SetCC;
15536     }
15537   }
15538   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
15539       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
15540       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15541
15542     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
15543     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
15544   }
15545
15546   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
15547   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
15548   if (X86CC == X86::COND_INVALID)
15549     return SDValue();
15550
15551   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
15552   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
15553   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15554                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
15555   if (VT == MVT::i1)
15556     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15557   return SetCC;
15558 }
15559
15560 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
15561 static bool isX86LogicalCmp(SDValue Op) {
15562   unsigned Opc = Op.getNode()->getOpcode();
15563   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
15564       Opc == X86ISD::SAHF)
15565     return true;
15566   if (Op.getResNo() == 1 &&
15567       (Opc == X86ISD::ADD ||
15568        Opc == X86ISD::SUB ||
15569        Opc == X86ISD::ADC ||
15570        Opc == X86ISD::SBB ||
15571        Opc == X86ISD::SMUL ||
15572        Opc == X86ISD::UMUL ||
15573        Opc == X86ISD::INC ||
15574        Opc == X86ISD::DEC ||
15575        Opc == X86ISD::OR ||
15576        Opc == X86ISD::XOR ||
15577        Opc == X86ISD::AND))
15578     return true;
15579
15580   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15581     return true;
15582
15583   return false;
15584 }
15585
15586 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15587   if (V.getOpcode() != ISD::TRUNCATE)
15588     return false;
15589
15590   SDValue VOp0 = V.getOperand(0);
15591   unsigned InBits = VOp0.getValueSizeInBits();
15592   unsigned Bits = V.getValueSizeInBits();
15593   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15594 }
15595
15596 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15597   bool addTest = true;
15598   SDValue Cond  = Op.getOperand(0);
15599   SDValue Op1 = Op.getOperand(1);
15600   SDValue Op2 = Op.getOperand(2);
15601   SDLoc DL(Op);
15602   EVT VT = Op1.getValueType();
15603   SDValue CC;
15604
15605   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15606   // are available. Otherwise fp cmovs get lowered into a less efficient branch
15607   // sequence later on.
15608   if (Cond.getOpcode() == ISD::SETCC &&
15609       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15610        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15611       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
15612     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15613     int SSECC = translateX86FSETCC(
15614         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15615
15616     if (SSECC != 8) {
15617       if (Subtarget->hasAVX512()) {
15618         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15619                                   DAG.getConstant(SSECC, MVT::i8));
15620         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15621       }
15622       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15623                                 DAG.getConstant(SSECC, MVT::i8));
15624       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15625       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15626       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15627     }
15628   }
15629
15630   if (Cond.getOpcode() == ISD::SETCC) {
15631     SDValue NewCond = LowerSETCC(Cond, DAG);
15632     if (NewCond.getNode())
15633       Cond = NewCond;
15634   }
15635
15636   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15637   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15638   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15639   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15640   if (Cond.getOpcode() == X86ISD::SETCC &&
15641       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15642       isZero(Cond.getOperand(1).getOperand(1))) {
15643     SDValue Cmp = Cond.getOperand(1);
15644
15645     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15646
15647     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
15648         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15649       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
15650
15651       SDValue CmpOp0 = Cmp.getOperand(0);
15652       // Apply further optimizations for special cases
15653       // (select (x != 0), -1, 0) -> neg & sbb
15654       // (select (x == 0), 0, -1) -> neg & sbb
15655       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
15656         if (YC->isNullValue() &&
15657             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
15658           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15659           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15660                                     DAG.getConstant(0, CmpOp0.getValueType()),
15661                                     CmpOp0);
15662           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15663                                     DAG.getConstant(X86::COND_B, MVT::i8),
15664                                     SDValue(Neg.getNode(), 1));
15665           return Res;
15666         }
15667
15668       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15669                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
15670       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15671
15672       SDValue Res =   // Res = 0 or -1.
15673         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15674                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
15675
15676       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
15677         Res = DAG.getNOT(DL, Res, Res.getValueType());
15678
15679       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
15680       if (!N2C || !N2C->isNullValue())
15681         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15682       return Res;
15683     }
15684   }
15685
15686   // Look past (and (setcc_carry (cmp ...)), 1).
15687   if (Cond.getOpcode() == ISD::AND &&
15688       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15689     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15690     if (C && C->getAPIntValue() == 1)
15691       Cond = Cond.getOperand(0);
15692   }
15693
15694   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15695   // setting operand in place of the X86ISD::SETCC.
15696   unsigned CondOpcode = Cond.getOpcode();
15697   if (CondOpcode == X86ISD::SETCC ||
15698       CondOpcode == X86ISD::SETCC_CARRY) {
15699     CC = Cond.getOperand(0);
15700
15701     SDValue Cmp = Cond.getOperand(1);
15702     unsigned Opc = Cmp.getOpcode();
15703     MVT VT = Op.getSimpleValueType();
15704
15705     bool IllegalFPCMov = false;
15706     if (VT.isFloatingPoint() && !VT.isVector() &&
15707         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15708       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15709
15710     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15711         Opc == X86ISD::BT) { // FIXME
15712       Cond = Cmp;
15713       addTest = false;
15714     }
15715   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15716              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15717              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15718               Cond.getOperand(0).getValueType() != MVT::i8)) {
15719     SDValue LHS = Cond.getOperand(0);
15720     SDValue RHS = Cond.getOperand(1);
15721     unsigned X86Opcode;
15722     unsigned X86Cond;
15723     SDVTList VTs;
15724     switch (CondOpcode) {
15725     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15726     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15727     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15728     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15729     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15730     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15731     default: llvm_unreachable("unexpected overflowing operator");
15732     }
15733     if (CondOpcode == ISD::UMULO)
15734       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15735                           MVT::i32);
15736     else
15737       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15738
15739     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15740
15741     if (CondOpcode == ISD::UMULO)
15742       Cond = X86Op.getValue(2);
15743     else
15744       Cond = X86Op.getValue(1);
15745
15746     CC = DAG.getConstant(X86Cond, MVT::i8);
15747     addTest = false;
15748   }
15749
15750   if (addTest) {
15751     // Look pass the truncate if the high bits are known zero.
15752     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15753         Cond = Cond.getOperand(0);
15754
15755     // We know the result of AND is compared against zero. Try to match
15756     // it to BT.
15757     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15758       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
15759       if (NewSetCC.getNode()) {
15760         CC = NewSetCC.getOperand(0);
15761         Cond = NewSetCC.getOperand(1);
15762         addTest = false;
15763       }
15764     }
15765   }
15766
15767   if (addTest) {
15768     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15769     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15770   }
15771
15772   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15773   // a <  b ?  0 : -1 -> RES = setcc_carry
15774   // a >= b ? -1 :  0 -> RES = setcc_carry
15775   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15776   if (Cond.getOpcode() == X86ISD::SUB) {
15777     Cond = ConvertCmpIfNecessary(Cond, DAG);
15778     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15779
15780     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15781         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
15782       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15783                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
15784       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
15785         return DAG.getNOT(DL, Res, Res.getValueType());
15786       return Res;
15787     }
15788   }
15789
15790   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15791   // widen the cmov and push the truncate through. This avoids introducing a new
15792   // branch during isel and doesn't add any extensions.
15793   if (Op.getValueType() == MVT::i8 &&
15794       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15795     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15796     if (T1.getValueType() == T2.getValueType() &&
15797         // Blacklist CopyFromReg to avoid partial register stalls.
15798         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15799       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15800       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15801       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15802     }
15803   }
15804
15805   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15806   // condition is true.
15807   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15808   SDValue Ops[] = { Op2, Op1, CC, Cond };
15809   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15810 }
15811
15812 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
15813                                        SelectionDAG &DAG) {
15814   MVT VT = Op->getSimpleValueType(0);
15815   SDValue In = Op->getOperand(0);
15816   MVT InVT = In.getSimpleValueType();
15817   MVT VTElt = VT.getVectorElementType();
15818   MVT InVTElt = InVT.getVectorElementType();
15819   SDLoc dl(Op);
15820
15821   // SKX processor
15822   if ((InVTElt == MVT::i1) &&
15823       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15824         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15825
15826        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15827         VTElt.getSizeInBits() <= 16)) ||
15828
15829        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15830         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15831
15832        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15833         VTElt.getSizeInBits() >= 32))))
15834     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15835
15836   unsigned int NumElts = VT.getVectorNumElements();
15837
15838   if (NumElts != 8 && NumElts != 16)
15839     return SDValue();
15840
15841   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15842     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15843       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15844     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15845   }
15846
15847   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15848   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15849
15850   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
15851   Constant *C = ConstantInt::get(*DAG.getContext(),
15852     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
15853
15854   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
15855   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
15856   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
15857                           MachinePointerInfo::getConstantPool(),
15858                           false, false, false, Alignment);
15859   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
15860   if (VT.is512BitVector())
15861     return Brcst;
15862   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
15863 }
15864
15865 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15866                                 SelectionDAG &DAG) {
15867   MVT VT = Op->getSimpleValueType(0);
15868   SDValue In = Op->getOperand(0);
15869   MVT InVT = In.getSimpleValueType();
15870   SDLoc dl(Op);
15871
15872   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15873     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15874
15875   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15876       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15877       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15878     return SDValue();
15879
15880   if (Subtarget->hasInt256())
15881     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15882
15883   // Optimize vectors in AVX mode
15884   // Sign extend  v8i16 to v8i32 and
15885   //              v4i32 to v4i64
15886   //
15887   // Divide input vector into two parts
15888   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15889   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15890   // concat the vectors to original VT
15891
15892   unsigned NumElems = InVT.getVectorNumElements();
15893   SDValue Undef = DAG.getUNDEF(InVT);
15894
15895   SmallVector<int,8> ShufMask1(NumElems, -1);
15896   for (unsigned i = 0; i != NumElems/2; ++i)
15897     ShufMask1[i] = i;
15898
15899   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15900
15901   SmallVector<int,8> ShufMask2(NumElems, -1);
15902   for (unsigned i = 0; i != NumElems/2; ++i)
15903     ShufMask2[i] = i + NumElems/2;
15904
15905   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15906
15907   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15908                                 VT.getVectorNumElements()/2);
15909
15910   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15911   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15912
15913   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15914 }
15915
15916 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15917 // may emit an illegal shuffle but the expansion is still better than scalar
15918 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15919 // we'll emit a shuffle and a arithmetic shift.
15920 // TODO: It is possible to support ZExt by zeroing the undef values during
15921 // the shuffle phase or after the shuffle.
15922 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15923                                  SelectionDAG &DAG) {
15924   MVT RegVT = Op.getSimpleValueType();
15925   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15926   assert(RegVT.isInteger() &&
15927          "We only custom lower integer vector sext loads.");
15928
15929   // Nothing useful we can do without SSE2 shuffles.
15930   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15931
15932   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15933   SDLoc dl(Ld);
15934   EVT MemVT = Ld->getMemoryVT();
15935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15936   unsigned RegSz = RegVT.getSizeInBits();
15937
15938   ISD::LoadExtType Ext = Ld->getExtensionType();
15939
15940   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15941          && "Only anyext and sext are currently implemented.");
15942   assert(MemVT != RegVT && "Cannot extend to the same type");
15943   assert(MemVT.isVector() && "Must load a vector from memory");
15944
15945   unsigned NumElems = RegVT.getVectorNumElements();
15946   unsigned MemSz = MemVT.getSizeInBits();
15947   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15948
15949   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15950     // The only way in which we have a legal 256-bit vector result but not the
15951     // integer 256-bit operations needed to directly lower a sextload is if we
15952     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15953     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15954     // correctly legalized. We do this late to allow the canonical form of
15955     // sextload to persist throughout the rest of the DAG combiner -- it wants
15956     // to fold together any extensions it can, and so will fuse a sign_extend
15957     // of an sextload into a sextload targeting a wider value.
15958     SDValue Load;
15959     if (MemSz == 128) {
15960       // Just switch this to a normal load.
15961       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15962                                        "it must be a legal 128-bit vector "
15963                                        "type!");
15964       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15965                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15966                   Ld->isInvariant(), Ld->getAlignment());
15967     } else {
15968       assert(MemSz < 128 &&
15969              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15970       // Do an sext load to a 128-bit vector type. We want to use the same
15971       // number of elements, but elements half as wide. This will end up being
15972       // recursively lowered by this routine, but will succeed as we definitely
15973       // have all the necessary features if we're using AVX1.
15974       EVT HalfEltVT =
15975           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15976       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15977       Load =
15978           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15979                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15980                          Ld->isNonTemporal(), Ld->isInvariant(),
15981                          Ld->getAlignment());
15982     }
15983
15984     // Replace chain users with the new chain.
15985     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15986     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15987
15988     // Finally, do a normal sign-extend to the desired register.
15989     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15990   }
15991
15992   // All sizes must be a power of two.
15993   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15994          "Non-power-of-two elements are not custom lowered!");
15995
15996   // Attempt to load the original value using scalar loads.
15997   // Find the largest scalar type that divides the total loaded size.
15998   MVT SclrLoadTy = MVT::i8;
15999   for (MVT Tp : MVT::integer_valuetypes()) {
16000     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16001       SclrLoadTy = Tp;
16002     }
16003   }
16004
16005   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16006   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16007       (64 <= MemSz))
16008     SclrLoadTy = MVT::f64;
16009
16010   // Calculate the number of scalar loads that we need to perform
16011   // in order to load our vector from memory.
16012   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16013
16014   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
16015          "Can only lower sext loads with a single scalar load!");
16016
16017   unsigned loadRegZize = RegSz;
16018   if (Ext == ISD::SEXTLOAD && RegSz == 256)
16019     loadRegZize /= 2;
16020
16021   // Represent our vector as a sequence of elements which are the
16022   // largest scalar that we can load.
16023   EVT LoadUnitVecVT = EVT::getVectorVT(
16024       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
16025
16026   // Represent the data using the same element type that is stored in
16027   // memory. In practice, we ''widen'' MemVT.
16028   EVT WideVecVT =
16029       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16030                        loadRegZize / MemVT.getScalarType().getSizeInBits());
16031
16032   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16033          "Invalid vector type");
16034
16035   // We can't shuffle using an illegal type.
16036   assert(TLI.isTypeLegal(WideVecVT) &&
16037          "We only lower types that form legal widened vector types");
16038
16039   SmallVector<SDValue, 8> Chains;
16040   SDValue Ptr = Ld->getBasePtr();
16041   SDValue Increment =
16042       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
16043   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16044
16045   for (unsigned i = 0; i < NumLoads; ++i) {
16046     // Perform a single load.
16047     SDValue ScalarLoad =
16048         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
16049                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
16050                     Ld->getAlignment());
16051     Chains.push_back(ScalarLoad.getValue(1));
16052     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16053     // another round of DAGCombining.
16054     if (i == 0)
16055       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16056     else
16057       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16058                         ScalarLoad, DAG.getIntPtrConstant(i));
16059
16060     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16061   }
16062
16063   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
16064
16065   // Bitcast the loaded value to a vector of the original element type, in
16066   // the size of the target vector type.
16067   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16068   unsigned SizeRatio = RegSz / MemSz;
16069
16070   if (Ext == ISD::SEXTLOAD) {
16071     // If we have SSE4.1, we can directly emit a VSEXT node.
16072     if (Subtarget->hasSSE41()) {
16073       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16074       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16075       return Sext;
16076     }
16077
16078     // Otherwise we'll shuffle the small elements in the high bits of the
16079     // larger type and perform an arithmetic shift. If the shift is not legal
16080     // it's better to scalarize.
16081     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
16082            "We can't implement a sext load without an arithmetic right shift!");
16083
16084     // Redistribute the loaded elements into the different locations.
16085     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16086     for (unsigned i = 0; i != NumElems; ++i)
16087       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
16088
16089     SDValue Shuff = DAG.getVectorShuffle(
16090         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16091
16092     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16093
16094     // Build the arithmetic shift.
16095     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16096                    MemVT.getVectorElementType().getSizeInBits();
16097     Shuff =
16098         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
16099
16100     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16101     return Shuff;
16102   }
16103
16104   // Redistribute the loaded elements into the different locations.
16105   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16106   for (unsigned i = 0; i != NumElems; ++i)
16107     ShuffleVec[i * SizeRatio] = i;
16108
16109   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16110                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16111
16112   // Bitcast to the requested type.
16113   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16114   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16115   return Shuff;
16116 }
16117
16118 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
16119 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
16120 // from the AND / OR.
16121 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
16122   Opc = Op.getOpcode();
16123   if (Opc != ISD::OR && Opc != ISD::AND)
16124     return false;
16125   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16126           Op.getOperand(0).hasOneUse() &&
16127           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
16128           Op.getOperand(1).hasOneUse());
16129 }
16130
16131 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
16132 // 1 and that the SETCC node has a single use.
16133 static bool isXor1OfSetCC(SDValue Op) {
16134   if (Op.getOpcode() != ISD::XOR)
16135     return false;
16136   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16137   if (N1C && N1C->getAPIntValue() == 1) {
16138     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16139       Op.getOperand(0).hasOneUse();
16140   }
16141   return false;
16142 }
16143
16144 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
16145   bool addTest = true;
16146   SDValue Chain = Op.getOperand(0);
16147   SDValue Cond  = Op.getOperand(1);
16148   SDValue Dest  = Op.getOperand(2);
16149   SDLoc dl(Op);
16150   SDValue CC;
16151   bool Inverted = false;
16152
16153   if (Cond.getOpcode() == ISD::SETCC) {
16154     // Check for setcc([su]{add,sub,mul}o == 0).
16155     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
16156         isa<ConstantSDNode>(Cond.getOperand(1)) &&
16157         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
16158         Cond.getOperand(0).getResNo() == 1 &&
16159         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
16160          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
16161          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
16162          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
16163          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
16164          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
16165       Inverted = true;
16166       Cond = Cond.getOperand(0);
16167     } else {
16168       SDValue NewCond = LowerSETCC(Cond, DAG);
16169       if (NewCond.getNode())
16170         Cond = NewCond;
16171     }
16172   }
16173 #if 0
16174   // FIXME: LowerXALUO doesn't handle these!!
16175   else if (Cond.getOpcode() == X86ISD::ADD  ||
16176            Cond.getOpcode() == X86ISD::SUB  ||
16177            Cond.getOpcode() == X86ISD::SMUL ||
16178            Cond.getOpcode() == X86ISD::UMUL)
16179     Cond = LowerXALUO(Cond, DAG);
16180 #endif
16181
16182   // Look pass (and (setcc_carry (cmp ...)), 1).
16183   if (Cond.getOpcode() == ISD::AND &&
16184       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
16185     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
16186     if (C && C->getAPIntValue() == 1)
16187       Cond = Cond.getOperand(0);
16188   }
16189
16190   // If condition flag is set by a X86ISD::CMP, then use it as the condition
16191   // setting operand in place of the X86ISD::SETCC.
16192   unsigned CondOpcode = Cond.getOpcode();
16193   if (CondOpcode == X86ISD::SETCC ||
16194       CondOpcode == X86ISD::SETCC_CARRY) {
16195     CC = Cond.getOperand(0);
16196
16197     SDValue Cmp = Cond.getOperand(1);
16198     unsigned Opc = Cmp.getOpcode();
16199     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
16200     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
16201       Cond = Cmp;
16202       addTest = false;
16203     } else {
16204       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
16205       default: break;
16206       case X86::COND_O:
16207       case X86::COND_B:
16208         // These can only come from an arithmetic instruction with overflow,
16209         // e.g. SADDO, UADDO.
16210         Cond = Cond.getNode()->getOperand(1);
16211         addTest = false;
16212         break;
16213       }
16214     }
16215   }
16216   CondOpcode = Cond.getOpcode();
16217   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
16218       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
16219       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
16220        Cond.getOperand(0).getValueType() != MVT::i8)) {
16221     SDValue LHS = Cond.getOperand(0);
16222     SDValue RHS = Cond.getOperand(1);
16223     unsigned X86Opcode;
16224     unsigned X86Cond;
16225     SDVTList VTs;
16226     // Keep this in sync with LowerXALUO, otherwise we might create redundant
16227     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
16228     // X86ISD::INC).
16229     switch (CondOpcode) {
16230     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
16231     case ISD::SADDO:
16232       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16233         if (C->isOne()) {
16234           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
16235           break;
16236         }
16237       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
16238     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
16239     case ISD::SSUBO:
16240       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16241         if (C->isOne()) {
16242           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
16243           break;
16244         }
16245       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
16246     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
16247     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
16248     default: llvm_unreachable("unexpected overflowing operator");
16249     }
16250     if (Inverted)
16251       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
16252     if (CondOpcode == ISD::UMULO)
16253       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
16254                           MVT::i32);
16255     else
16256       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
16257
16258     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
16259
16260     if (CondOpcode == ISD::UMULO)
16261       Cond = X86Op.getValue(2);
16262     else
16263       Cond = X86Op.getValue(1);
16264
16265     CC = DAG.getConstant(X86Cond, MVT::i8);
16266     addTest = false;
16267   } else {
16268     unsigned CondOpc;
16269     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
16270       SDValue Cmp = Cond.getOperand(0).getOperand(1);
16271       if (CondOpc == ISD::OR) {
16272         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
16273         // two branches instead of an explicit OR instruction with a
16274         // separate test.
16275         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16276             isX86LogicalCmp(Cmp)) {
16277           CC = Cond.getOperand(0).getOperand(0);
16278           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16279                               Chain, Dest, CC, Cmp);
16280           CC = Cond.getOperand(1).getOperand(0);
16281           Cond = Cmp;
16282           addTest = false;
16283         }
16284       } else { // ISD::AND
16285         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
16286         // two branches instead of an explicit AND instruction with a
16287         // separate test. However, we only do this if this block doesn't
16288         // have a fall-through edge, because this requires an explicit
16289         // jmp when the condition is false.
16290         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16291             isX86LogicalCmp(Cmp) &&
16292             Op.getNode()->hasOneUse()) {
16293           X86::CondCode CCode =
16294             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16295           CCode = X86::GetOppositeBranchCondition(CCode);
16296           CC = DAG.getConstant(CCode, MVT::i8);
16297           SDNode *User = *Op.getNode()->use_begin();
16298           // Look for an unconditional branch following this conditional branch.
16299           // We need this because we need to reverse the successors in order
16300           // to implement FCMP_OEQ.
16301           if (User->getOpcode() == ISD::BR) {
16302             SDValue FalseBB = User->getOperand(1);
16303             SDNode *NewBR =
16304               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16305             assert(NewBR == User);
16306             (void)NewBR;
16307             Dest = FalseBB;
16308
16309             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16310                                 Chain, Dest, CC, Cmp);
16311             X86::CondCode CCode =
16312               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
16313             CCode = X86::GetOppositeBranchCondition(CCode);
16314             CC = DAG.getConstant(CCode, MVT::i8);
16315             Cond = Cmp;
16316             addTest = false;
16317           }
16318         }
16319       }
16320     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
16321       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
16322       // It should be transformed during dag combiner except when the condition
16323       // is set by a arithmetics with overflow node.
16324       X86::CondCode CCode =
16325         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16326       CCode = X86::GetOppositeBranchCondition(CCode);
16327       CC = DAG.getConstant(CCode, MVT::i8);
16328       Cond = Cond.getOperand(0).getOperand(1);
16329       addTest = false;
16330     } else if (Cond.getOpcode() == ISD::SETCC &&
16331                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
16332       // For FCMP_OEQ, we can emit
16333       // two branches instead of an explicit AND instruction with a
16334       // separate test. However, we only do this if this block doesn't
16335       // have a fall-through edge, because this requires an explicit
16336       // jmp when the condition is false.
16337       if (Op.getNode()->hasOneUse()) {
16338         SDNode *User = *Op.getNode()->use_begin();
16339         // Look for an unconditional branch following this conditional branch.
16340         // We need this because we need to reverse the successors in order
16341         // to implement FCMP_OEQ.
16342         if (User->getOpcode() == ISD::BR) {
16343           SDValue FalseBB = User->getOperand(1);
16344           SDNode *NewBR =
16345             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16346           assert(NewBR == User);
16347           (void)NewBR;
16348           Dest = FalseBB;
16349
16350           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16351                                     Cond.getOperand(0), Cond.getOperand(1));
16352           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16353           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16354           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16355                               Chain, Dest, CC, Cmp);
16356           CC = DAG.getConstant(X86::COND_P, MVT::i8);
16357           Cond = Cmp;
16358           addTest = false;
16359         }
16360       }
16361     } else if (Cond.getOpcode() == ISD::SETCC &&
16362                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
16363       // For FCMP_UNE, we can emit
16364       // two branches instead of an explicit AND instruction with a
16365       // separate test. However, we only do this if this block doesn't
16366       // have a fall-through edge, because this requires an explicit
16367       // jmp when the condition is false.
16368       if (Op.getNode()->hasOneUse()) {
16369         SDNode *User = *Op.getNode()->use_begin();
16370         // Look for an unconditional branch following this conditional branch.
16371         // We need this because we need to reverse the successors in order
16372         // to implement FCMP_UNE.
16373         if (User->getOpcode() == ISD::BR) {
16374           SDValue FalseBB = User->getOperand(1);
16375           SDNode *NewBR =
16376             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16377           assert(NewBR == User);
16378           (void)NewBR;
16379
16380           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16381                                     Cond.getOperand(0), Cond.getOperand(1));
16382           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16383           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16384           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16385                               Chain, Dest, CC, Cmp);
16386           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
16387           Cond = Cmp;
16388           addTest = false;
16389           Dest = FalseBB;
16390         }
16391       }
16392     }
16393   }
16394
16395   if (addTest) {
16396     // Look pass the truncate if the high bits are known zero.
16397     if (isTruncWithZeroHighBitsInput(Cond, DAG))
16398         Cond = Cond.getOperand(0);
16399
16400     // We know the result of AND is compared against zero. Try to match
16401     // it to BT.
16402     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16403       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
16404       if (NewSetCC.getNode()) {
16405         CC = NewSetCC.getOperand(0);
16406         Cond = NewSetCC.getOperand(1);
16407         addTest = false;
16408       }
16409     }
16410   }
16411
16412   if (addTest) {
16413     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
16414     CC = DAG.getConstant(X86Cond, MVT::i8);
16415     Cond = EmitTest(Cond, X86Cond, dl, DAG);
16416   }
16417   Cond = ConvertCmpIfNecessary(Cond, DAG);
16418   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16419                      Chain, Dest, CC, Cond);
16420 }
16421
16422 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
16423 // Calls to _alloca are needed to probe the stack when allocating more than 4k
16424 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
16425 // that the guard pages used by the OS virtual memory manager are allocated in
16426 // correct sequence.
16427 SDValue
16428 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
16429                                            SelectionDAG &DAG) const {
16430   MachineFunction &MF = DAG.getMachineFunction();
16431   bool SplitStack = MF.shouldSplitStack();
16432   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
16433                SplitStack;
16434   SDLoc dl(Op);
16435
16436   if (!Lower) {
16437     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16438     SDNode* Node = Op.getNode();
16439
16440     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
16441     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
16442         " not tell us which reg is the stack pointer!");
16443     EVT VT = Node->getValueType(0);
16444     SDValue Tmp1 = SDValue(Node, 0);
16445     SDValue Tmp2 = SDValue(Node, 1);
16446     SDValue Tmp3 = Node->getOperand(2);
16447     SDValue Chain = Tmp1.getOperand(0);
16448
16449     // Chain the dynamic stack allocation so that it doesn't modify the stack
16450     // pointer when other instructions are using the stack.
16451     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
16452         SDLoc(Node));
16453
16454     SDValue Size = Tmp2.getOperand(1);
16455     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
16456     Chain = SP.getValue(1);
16457     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
16458     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
16459     unsigned StackAlign = TFI.getStackAlignment();
16460     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
16461     if (Align > StackAlign)
16462       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
16463           DAG.getConstant(-(uint64_t)Align, VT));
16464     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
16465
16466     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
16467         DAG.getIntPtrConstant(0, true), SDValue(),
16468         SDLoc(Node));
16469
16470     SDValue Ops[2] = { Tmp1, Tmp2 };
16471     return DAG.getMergeValues(Ops, dl);
16472   }
16473
16474   // Get the inputs.
16475   SDValue Chain = Op.getOperand(0);
16476   SDValue Size  = Op.getOperand(1);
16477   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16478   EVT VT = Op.getNode()->getValueType(0);
16479
16480   bool Is64Bit = Subtarget->is64Bit();
16481   EVT SPTy = getPointerTy();
16482
16483   if (SplitStack) {
16484     MachineRegisterInfo &MRI = MF.getRegInfo();
16485
16486     if (Is64Bit) {
16487       // The 64 bit implementation of segmented stacks needs to clobber both r10
16488       // r11. This makes it impossible to use it along with nested parameters.
16489       const Function *F = MF.getFunction();
16490
16491       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16492            I != E; ++I)
16493         if (I->hasNestAttr())
16494           report_fatal_error("Cannot use segmented stacks with functions that "
16495                              "have nested arguments.");
16496     }
16497
16498     const TargetRegisterClass *AddrRegClass =
16499       getRegClassFor(getPointerTy());
16500     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16501     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16502     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16503                                 DAG.getRegister(Vreg, SPTy));
16504     SDValue Ops1[2] = { Value, Chain };
16505     return DAG.getMergeValues(Ops1, dl);
16506   } else {
16507     SDValue Flag;
16508     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16509
16510     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16511     Flag = Chain.getValue(1);
16512     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16513
16514     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16515
16516     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16517         DAG.getSubtarget().getRegisterInfo());
16518     unsigned SPReg = RegInfo->getStackRegister();
16519     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16520     Chain = SP.getValue(1);
16521
16522     if (Align) {
16523       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16524                        DAG.getConstant(-(uint64_t)Align, VT));
16525       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16526     }
16527
16528     SDValue Ops1[2] = { SP, Chain };
16529     return DAG.getMergeValues(Ops1, dl);
16530   }
16531 }
16532
16533 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16534   MachineFunction &MF = DAG.getMachineFunction();
16535   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16536
16537   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16538   SDLoc DL(Op);
16539
16540   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
16541     // vastart just stores the address of the VarArgsFrameIndex slot into the
16542     // memory location argument.
16543     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16544                                    getPointerTy());
16545     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16546                         MachinePointerInfo(SV), false, false, 0);
16547   }
16548
16549   // __va_list_tag:
16550   //   gp_offset         (0 - 6 * 8)
16551   //   fp_offset         (48 - 48 + 8 * 16)
16552   //   overflow_arg_area (point to parameters coming in memory).
16553   //   reg_save_area
16554   SmallVector<SDValue, 8> MemOps;
16555   SDValue FIN = Op.getOperand(1);
16556   // Store gp_offset
16557   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16558                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16559                                                MVT::i32),
16560                                FIN, MachinePointerInfo(SV), false, false, 0);
16561   MemOps.push_back(Store);
16562
16563   // Store fp_offset
16564   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16565                     FIN, DAG.getIntPtrConstant(4));
16566   Store = DAG.getStore(Op.getOperand(0), DL,
16567                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
16568                                        MVT::i32),
16569                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16570   MemOps.push_back(Store);
16571
16572   // Store ptr to overflow_arg_area
16573   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16574                     FIN, DAG.getIntPtrConstant(4));
16575   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16576                                     getPointerTy());
16577   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16578                        MachinePointerInfo(SV, 8),
16579                        false, false, 0);
16580   MemOps.push_back(Store);
16581
16582   // Store ptr to reg_save_area.
16583   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16584                     FIN, DAG.getIntPtrConstant(8));
16585   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
16586                                     getPointerTy());
16587   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
16588                        MachinePointerInfo(SV, 16), false, false, 0);
16589   MemOps.push_back(Store);
16590   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16591 }
16592
16593 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16594   assert(Subtarget->is64Bit() &&
16595          "LowerVAARG only handles 64-bit va_arg!");
16596   assert((Subtarget->isTargetLinux() ||
16597           Subtarget->isTargetDarwin()) &&
16598           "Unhandled target in LowerVAARG");
16599   assert(Op.getNode()->getNumOperands() == 4);
16600   SDValue Chain = Op.getOperand(0);
16601   SDValue SrcPtr = Op.getOperand(1);
16602   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16603   unsigned Align = Op.getConstantOperandVal(3);
16604   SDLoc dl(Op);
16605
16606   EVT ArgVT = Op.getNode()->getValueType(0);
16607   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16608   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
16609   uint8_t ArgMode;
16610
16611   // Decide which area this value should be read from.
16612   // TODO: Implement the AMD64 ABI in its entirety. This simple
16613   // selection mechanism works only for the basic types.
16614   if (ArgVT == MVT::f80) {
16615     llvm_unreachable("va_arg for f80 not yet implemented");
16616   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16617     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16618   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16619     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16620   } else {
16621     llvm_unreachable("Unhandled argument type in LowerVAARG");
16622   }
16623
16624   if (ArgMode == 2) {
16625     // Sanity Check: Make sure using fp_offset makes sense.
16626     assert(!DAG.getTarget().Options.UseSoftFloat &&
16627            !(DAG.getMachineFunction()
16628                 .getFunction()->getAttributes()
16629                 .hasAttribute(AttributeSet::FunctionIndex,
16630                               Attribute::NoImplicitFloat)) &&
16631            Subtarget->hasSSE1());
16632   }
16633
16634   // Insert VAARG_64 node into the DAG
16635   // VAARG_64 returns two values: Variable Argument Address, Chain
16636   SmallVector<SDValue, 11> InstOps;
16637   InstOps.push_back(Chain);
16638   InstOps.push_back(SrcPtr);
16639   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
16640   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
16641   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
16642   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
16643   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16644                                           VTs, InstOps, MVT::i64,
16645                                           MachinePointerInfo(SV),
16646                                           /*Align=*/0,
16647                                           /*Volatile=*/false,
16648                                           /*ReadMem=*/true,
16649                                           /*WriteMem=*/true);
16650   Chain = VAARG.getValue(1);
16651
16652   // Load the next argument and return it
16653   return DAG.getLoad(ArgVT, dl,
16654                      Chain,
16655                      VAARG,
16656                      MachinePointerInfo(),
16657                      false, false, false, 0);
16658 }
16659
16660 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16661                            SelectionDAG &DAG) {
16662   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
16663   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16664   SDValue Chain = Op.getOperand(0);
16665   SDValue DstPtr = Op.getOperand(1);
16666   SDValue SrcPtr = Op.getOperand(2);
16667   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16668   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16669   SDLoc DL(Op);
16670
16671   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16672                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
16673                        false,
16674                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16675 }
16676
16677 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16678 // amount is a constant. Takes immediate version of shift as input.
16679 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16680                                           SDValue SrcOp, uint64_t ShiftAmt,
16681                                           SelectionDAG &DAG) {
16682   MVT ElementType = VT.getVectorElementType();
16683
16684   // Fold this packed shift into its first operand if ShiftAmt is 0.
16685   if (ShiftAmt == 0)
16686     return SrcOp;
16687
16688   // Check for ShiftAmt >= element width
16689   if (ShiftAmt >= ElementType.getSizeInBits()) {
16690     if (Opc == X86ISD::VSRAI)
16691       ShiftAmt = ElementType.getSizeInBits() - 1;
16692     else
16693       return DAG.getConstant(0, VT);
16694   }
16695
16696   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16697          && "Unknown target vector shift-by-constant node");
16698
16699   // Fold this packed vector shift into a build vector if SrcOp is a
16700   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16701   if (VT == SrcOp.getSimpleValueType() &&
16702       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16703     SmallVector<SDValue, 8> Elts;
16704     unsigned NumElts = SrcOp->getNumOperands();
16705     ConstantSDNode *ND;
16706
16707     switch(Opc) {
16708     default: llvm_unreachable(nullptr);
16709     case X86ISD::VSHLI:
16710       for (unsigned i=0; i!=NumElts; ++i) {
16711         SDValue CurrentOp = SrcOp->getOperand(i);
16712         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16713           Elts.push_back(CurrentOp);
16714           continue;
16715         }
16716         ND = cast<ConstantSDNode>(CurrentOp);
16717         const APInt &C = ND->getAPIntValue();
16718         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
16719       }
16720       break;
16721     case X86ISD::VSRLI:
16722       for (unsigned i=0; i!=NumElts; ++i) {
16723         SDValue CurrentOp = SrcOp->getOperand(i);
16724         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16725           Elts.push_back(CurrentOp);
16726           continue;
16727         }
16728         ND = cast<ConstantSDNode>(CurrentOp);
16729         const APInt &C = ND->getAPIntValue();
16730         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
16731       }
16732       break;
16733     case X86ISD::VSRAI:
16734       for (unsigned i=0; i!=NumElts; ++i) {
16735         SDValue CurrentOp = SrcOp->getOperand(i);
16736         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16737           Elts.push_back(CurrentOp);
16738           continue;
16739         }
16740         ND = cast<ConstantSDNode>(CurrentOp);
16741         const APInt &C = ND->getAPIntValue();
16742         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
16743       }
16744       break;
16745     }
16746
16747     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16748   }
16749
16750   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
16751 }
16752
16753 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16754 // may or may not be a constant. Takes immediate version of shift as input.
16755 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16756                                    SDValue SrcOp, SDValue ShAmt,
16757                                    SelectionDAG &DAG) {
16758   MVT SVT = ShAmt.getSimpleValueType();
16759   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16760
16761   // Catch shift-by-constant.
16762   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16763     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16764                                       CShAmt->getZExtValue(), DAG);
16765
16766   // Change opcode to non-immediate version
16767   switch (Opc) {
16768     default: llvm_unreachable("Unknown target vector shift node");
16769     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16770     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16771     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16772   }
16773
16774   const X86Subtarget &Subtarget =
16775       DAG.getTarget().getSubtarget<X86Subtarget>();
16776   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16777       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16778     // Let the shuffle legalizer expand this shift amount node.
16779     SDValue Op0 = ShAmt.getOperand(0);
16780     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16781     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16782   } else {
16783     // Need to build a vector containing shift amount.
16784     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16785     SmallVector<SDValue, 4> ShOps;
16786     ShOps.push_back(ShAmt);
16787     if (SVT == MVT::i32) {
16788       ShOps.push_back(DAG.getConstant(0, SVT));
16789       ShOps.push_back(DAG.getUNDEF(SVT));
16790     }
16791     ShOps.push_back(DAG.getUNDEF(SVT));
16792
16793     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16794     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16795   }
16796
16797   // The return type has to be a 128-bit type with the same element
16798   // type as the input type.
16799   MVT EltVT = VT.getVectorElementType();
16800   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16801
16802   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
16803   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16804 }
16805
16806 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16807 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16808 /// necessary casting for \p Mask when lowering masking intrinsics.
16809 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16810                                     SDValue PreservedSrc,
16811                                     const X86Subtarget *Subtarget,
16812                                     SelectionDAG &DAG) {
16813     EVT VT = Op.getValueType();
16814     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16815                                   MVT::i1, VT.getVectorNumElements());
16816     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16817                                      Mask.getValueType().getSizeInBits());
16818     SDLoc dl(Op);
16819
16820     assert(MaskVT.isSimple() && "invalid mask type");
16821
16822     if (isAllOnes(Mask))
16823       return Op;
16824
16825     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16826     // are extracted by EXTRACT_SUBVECTOR.
16827     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16828                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
16829                               DAG.getIntPtrConstant(0));
16830
16831     switch (Op.getOpcode()) {
16832       default: break;
16833       case X86ISD::PCMPEQM:
16834       case X86ISD::PCMPGTM:
16835       case X86ISD::CMPM:
16836       case X86ISD::CMPMU:
16837         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16838     }
16839     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16840       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16841     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
16842 }
16843
16844 /// \brief Creates an SDNode for a predicated scalar operation.
16845 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16846 /// The mask is comming as MVT::i8 and it should be truncated
16847 /// to MVT::i1 while lowering masking intrinsics.
16848 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16849 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
16850 /// a scalar instruction.
16851 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16852                                     SDValue PreservedSrc,
16853                                     const X86Subtarget *Subtarget,
16854                                     SelectionDAG &DAG) {
16855     if (isAllOnes(Mask))
16856       return Op;
16857
16858     EVT VT = Op.getValueType();
16859     SDLoc dl(Op);
16860     // The mask should be of type MVT::i1
16861     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16862
16863     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16864       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16865     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16866 }
16867
16868 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
16869     switch (IntNo) {
16870     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16871     case Intrinsic::x86_fma_vfmadd_ps:
16872     case Intrinsic::x86_fma_vfmadd_pd:
16873     case Intrinsic::x86_fma_vfmadd_ps_256:
16874     case Intrinsic::x86_fma_vfmadd_pd_256:
16875     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
16876     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
16877       return X86ISD::FMADD;
16878     case Intrinsic::x86_fma_vfmsub_ps:
16879     case Intrinsic::x86_fma_vfmsub_pd:
16880     case Intrinsic::x86_fma_vfmsub_ps_256:
16881     case Intrinsic::x86_fma_vfmsub_pd_256:
16882     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
16883     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
16884       return X86ISD::FMSUB;
16885     case Intrinsic::x86_fma_vfnmadd_ps:
16886     case Intrinsic::x86_fma_vfnmadd_pd:
16887     case Intrinsic::x86_fma_vfnmadd_ps_256:
16888     case Intrinsic::x86_fma_vfnmadd_pd_256:
16889     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
16890     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
16891       return X86ISD::FNMADD;
16892     case Intrinsic::x86_fma_vfnmsub_ps:
16893     case Intrinsic::x86_fma_vfnmsub_pd:
16894     case Intrinsic::x86_fma_vfnmsub_ps_256:
16895     case Intrinsic::x86_fma_vfnmsub_pd_256:
16896     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
16897     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
16898       return X86ISD::FNMSUB;
16899     case Intrinsic::x86_fma_vfmaddsub_ps:
16900     case Intrinsic::x86_fma_vfmaddsub_pd:
16901     case Intrinsic::x86_fma_vfmaddsub_ps_256:
16902     case Intrinsic::x86_fma_vfmaddsub_pd_256:
16903     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
16904     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
16905       return X86ISD::FMADDSUB;
16906     case Intrinsic::x86_fma_vfmsubadd_ps:
16907     case Intrinsic::x86_fma_vfmsubadd_pd:
16908     case Intrinsic::x86_fma_vfmsubadd_ps_256:
16909     case Intrinsic::x86_fma_vfmsubadd_pd_256:
16910     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
16911     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
16912       return X86ISD::FMSUBADD;
16913     }
16914 }
16915
16916 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16917                                        SelectionDAG &DAG) {
16918   SDLoc dl(Op);
16919   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16920   EVT VT = Op.getValueType();
16921   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16922   if (IntrData) {
16923     switch(IntrData->Type) {
16924     case INTR_TYPE_1OP:
16925       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16926     case INTR_TYPE_2OP:
16927       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16928         Op.getOperand(2));
16929     case INTR_TYPE_3OP:
16930       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16931         Op.getOperand(2), Op.getOperand(3));
16932     case INTR_TYPE_1OP_MASK_RM: {
16933       SDValue Src = Op.getOperand(1);
16934       SDValue Src0 = Op.getOperand(2);
16935       SDValue Mask = Op.getOperand(3);
16936       SDValue RoundingMode = Op.getOperand(4);
16937       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16938                                               RoundingMode),
16939                                   Mask, Src0, Subtarget, DAG);
16940     }
16941     case INTR_TYPE_SCALAR_MASK_RM: {
16942       SDValue Src1 = Op.getOperand(1);
16943       SDValue Src2 = Op.getOperand(2);
16944       SDValue Src0 = Op.getOperand(3);
16945       SDValue Mask = Op.getOperand(4);
16946       SDValue RoundingMode = Op.getOperand(5);
16947       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16948                                               RoundingMode),
16949                                   Mask, Src0, Subtarget, DAG);
16950     }
16951     case INTR_TYPE_2OP_MASK: {
16952       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Op.getOperand(1),
16953                                               Op.getOperand(2)),
16954                                   Op.getOperand(4), Op.getOperand(3), Subtarget, DAG);
16955     }
16956     case CMP_MASK:
16957     case CMP_MASK_CC: {
16958       // Comparison intrinsics with masks.
16959       // Example of transformation:
16960       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16961       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16962       // (i8 (bitcast
16963       //   (v8i1 (insert_subvector undef,
16964       //           (v2i1 (and (PCMPEQM %a, %b),
16965       //                      (extract_subvector
16966       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16967       EVT VT = Op.getOperand(1).getValueType();
16968       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16969                                     VT.getVectorNumElements());
16970       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16971       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16972                                        Mask.getValueType().getSizeInBits());
16973       SDValue Cmp;
16974       if (IntrData->Type == CMP_MASK_CC) {
16975         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16976                     Op.getOperand(2), Op.getOperand(3));
16977       } else {
16978         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16979         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16980                     Op.getOperand(2));
16981       }
16982       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16983                                              DAG.getTargetConstant(0, MaskVT),
16984                                              Subtarget, DAG);
16985       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16986                                 DAG.getUNDEF(BitcastVT), CmpMask,
16987                                 DAG.getIntPtrConstant(0));
16988       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
16989     }
16990     case COMI: { // Comparison intrinsics
16991       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16992       SDValue LHS = Op.getOperand(1);
16993       SDValue RHS = Op.getOperand(2);
16994       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
16995       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16996       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16997       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16998                                   DAG.getConstant(X86CC, MVT::i8), Cond);
16999       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17000     }
17001     case VSHIFT:
17002       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
17003                                  Op.getOperand(1), Op.getOperand(2), DAG);
17004     case VSHIFT_MASK:
17005       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
17006                                                       Op.getSimpleValueType(),
17007                                                       Op.getOperand(1),
17008                                                       Op.getOperand(2), DAG),
17009                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
17010                                   DAG);
17011     case COMPRESS_EXPAND_IN_REG: {
17012       SDValue Mask = Op.getOperand(3);
17013       SDValue DataToCompress = Op.getOperand(1);
17014       SDValue PassThru = Op.getOperand(2);
17015       if (isAllOnes(Mask)) // return data as is
17016         return Op.getOperand(1);
17017       EVT VT = Op.getValueType();
17018       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17019                                     VT.getVectorNumElements());
17020       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17021                                        Mask.getValueType().getSizeInBits());
17022       SDLoc dl(Op);
17023       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17024                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17025                                   DAG.getIntPtrConstant(0));
17026
17027       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
17028                          PassThru);
17029     }
17030     case BLEND: {
17031       SDValue Mask = Op.getOperand(3);
17032       EVT VT = Op.getValueType();
17033       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17034                                     VT.getVectorNumElements());
17035       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17036                                        Mask.getValueType().getSizeInBits());
17037       SDLoc dl(Op);
17038       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17039                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17040                                   DAG.getIntPtrConstant(0));
17041       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
17042                          Op.getOperand(2));
17043     }
17044     case FMA_OP_MASK:
17045     {
17046         return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
17047             dl, Op.getValueType(),
17048             Op.getOperand(1),
17049             Op.getOperand(2),
17050             Op.getOperand(3)),
17051             Op.getOperand(4), Op.getOperand(1),
17052             Subtarget, DAG);
17053     }
17054     default:
17055       break;
17056     }
17057   }
17058
17059   switch (IntNo) {
17060   default: return SDValue();    // Don't custom lower most intrinsics.
17061
17062   case Intrinsic::x86_avx512_mask_valign_q_512:
17063   case Intrinsic::x86_avx512_mask_valign_d_512:
17064     // Vector source operands are swapped.
17065     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
17066                                             Op.getValueType(), Op.getOperand(2),
17067                                             Op.getOperand(1),
17068                                             Op.getOperand(3)),
17069                                 Op.getOperand(5), Op.getOperand(4),
17070                                 Subtarget, DAG);
17071
17072   // ptest and testp intrinsics. The intrinsic these come from are designed to
17073   // return an integer value, not just an instruction so lower it to the ptest
17074   // or testp pattern and a setcc for the result.
17075   case Intrinsic::x86_sse41_ptestz:
17076   case Intrinsic::x86_sse41_ptestc:
17077   case Intrinsic::x86_sse41_ptestnzc:
17078   case Intrinsic::x86_avx_ptestz_256:
17079   case Intrinsic::x86_avx_ptestc_256:
17080   case Intrinsic::x86_avx_ptestnzc_256:
17081   case Intrinsic::x86_avx_vtestz_ps:
17082   case Intrinsic::x86_avx_vtestc_ps:
17083   case Intrinsic::x86_avx_vtestnzc_ps:
17084   case Intrinsic::x86_avx_vtestz_pd:
17085   case Intrinsic::x86_avx_vtestc_pd:
17086   case Intrinsic::x86_avx_vtestnzc_pd:
17087   case Intrinsic::x86_avx_vtestz_ps_256:
17088   case Intrinsic::x86_avx_vtestc_ps_256:
17089   case Intrinsic::x86_avx_vtestnzc_ps_256:
17090   case Intrinsic::x86_avx_vtestz_pd_256:
17091   case Intrinsic::x86_avx_vtestc_pd_256:
17092   case Intrinsic::x86_avx_vtestnzc_pd_256: {
17093     bool IsTestPacked = false;
17094     unsigned X86CC;
17095     switch (IntNo) {
17096     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17097     case Intrinsic::x86_avx_vtestz_ps:
17098     case Intrinsic::x86_avx_vtestz_pd:
17099     case Intrinsic::x86_avx_vtestz_ps_256:
17100     case Intrinsic::x86_avx_vtestz_pd_256:
17101       IsTestPacked = true; // Fallthrough
17102     case Intrinsic::x86_sse41_ptestz:
17103     case Intrinsic::x86_avx_ptestz_256:
17104       // ZF = 1
17105       X86CC = X86::COND_E;
17106       break;
17107     case Intrinsic::x86_avx_vtestc_ps:
17108     case Intrinsic::x86_avx_vtestc_pd:
17109     case Intrinsic::x86_avx_vtestc_ps_256:
17110     case Intrinsic::x86_avx_vtestc_pd_256:
17111       IsTestPacked = true; // Fallthrough
17112     case Intrinsic::x86_sse41_ptestc:
17113     case Intrinsic::x86_avx_ptestc_256:
17114       // CF = 1
17115       X86CC = X86::COND_B;
17116       break;
17117     case Intrinsic::x86_avx_vtestnzc_ps:
17118     case Intrinsic::x86_avx_vtestnzc_pd:
17119     case Intrinsic::x86_avx_vtestnzc_ps_256:
17120     case Intrinsic::x86_avx_vtestnzc_pd_256:
17121       IsTestPacked = true; // Fallthrough
17122     case Intrinsic::x86_sse41_ptestnzc:
17123     case Intrinsic::x86_avx_ptestnzc_256:
17124       // ZF and CF = 0
17125       X86CC = X86::COND_A;
17126       break;
17127     }
17128
17129     SDValue LHS = Op.getOperand(1);
17130     SDValue RHS = Op.getOperand(2);
17131     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17132     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17133     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17134     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17135     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17136   }
17137   case Intrinsic::x86_avx512_kortestz_w:
17138   case Intrinsic::x86_avx512_kortestc_w: {
17139     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17140     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
17141     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
17142     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17143     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17144     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17145     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17146   }
17147
17148   case Intrinsic::x86_sse42_pcmpistria128:
17149   case Intrinsic::x86_sse42_pcmpestria128:
17150   case Intrinsic::x86_sse42_pcmpistric128:
17151   case Intrinsic::x86_sse42_pcmpestric128:
17152   case Intrinsic::x86_sse42_pcmpistrio128:
17153   case Intrinsic::x86_sse42_pcmpestrio128:
17154   case Intrinsic::x86_sse42_pcmpistris128:
17155   case Intrinsic::x86_sse42_pcmpestris128:
17156   case Intrinsic::x86_sse42_pcmpistriz128:
17157   case Intrinsic::x86_sse42_pcmpestriz128: {
17158     unsigned Opcode;
17159     unsigned X86CC;
17160     switch (IntNo) {
17161     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17162     case Intrinsic::x86_sse42_pcmpistria128:
17163       Opcode = X86ISD::PCMPISTRI;
17164       X86CC = X86::COND_A;
17165       break;
17166     case Intrinsic::x86_sse42_pcmpestria128:
17167       Opcode = X86ISD::PCMPESTRI;
17168       X86CC = X86::COND_A;
17169       break;
17170     case Intrinsic::x86_sse42_pcmpistric128:
17171       Opcode = X86ISD::PCMPISTRI;
17172       X86CC = X86::COND_B;
17173       break;
17174     case Intrinsic::x86_sse42_pcmpestric128:
17175       Opcode = X86ISD::PCMPESTRI;
17176       X86CC = X86::COND_B;
17177       break;
17178     case Intrinsic::x86_sse42_pcmpistrio128:
17179       Opcode = X86ISD::PCMPISTRI;
17180       X86CC = X86::COND_O;
17181       break;
17182     case Intrinsic::x86_sse42_pcmpestrio128:
17183       Opcode = X86ISD::PCMPESTRI;
17184       X86CC = X86::COND_O;
17185       break;
17186     case Intrinsic::x86_sse42_pcmpistris128:
17187       Opcode = X86ISD::PCMPISTRI;
17188       X86CC = X86::COND_S;
17189       break;
17190     case Intrinsic::x86_sse42_pcmpestris128:
17191       Opcode = X86ISD::PCMPESTRI;
17192       X86CC = X86::COND_S;
17193       break;
17194     case Intrinsic::x86_sse42_pcmpistriz128:
17195       Opcode = X86ISD::PCMPISTRI;
17196       X86CC = X86::COND_E;
17197       break;
17198     case Intrinsic::x86_sse42_pcmpestriz128:
17199       Opcode = X86ISD::PCMPESTRI;
17200       X86CC = X86::COND_E;
17201       break;
17202     }
17203     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17204     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17205     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17206     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17207                                 DAG.getConstant(X86CC, MVT::i8),
17208                                 SDValue(PCMP.getNode(), 1));
17209     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17210   }
17211
17212   case Intrinsic::x86_sse42_pcmpistri128:
17213   case Intrinsic::x86_sse42_pcmpestri128: {
17214     unsigned Opcode;
17215     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17216       Opcode = X86ISD::PCMPISTRI;
17217     else
17218       Opcode = X86ISD::PCMPESTRI;
17219
17220     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17221     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17222     return DAG.getNode(Opcode, dl, VTs, NewOps);
17223   }
17224
17225   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
17226   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
17227   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
17228   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
17229   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
17230   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
17231   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
17232   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
17233   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
17234   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
17235   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
17236   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
17237     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
17238     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
17239       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
17240                                               dl, Op.getValueType(),
17241                                               Op.getOperand(1),
17242                                               Op.getOperand(2),
17243                                               Op.getOperand(3)),
17244                                   Op.getOperand(4), Op.getOperand(1),
17245                                   Subtarget, DAG);
17246     else
17247       return SDValue();
17248   }
17249
17250   case Intrinsic::x86_fma_vfmadd_ps:
17251   case Intrinsic::x86_fma_vfmadd_pd:
17252   case Intrinsic::x86_fma_vfmsub_ps:
17253   case Intrinsic::x86_fma_vfmsub_pd:
17254   case Intrinsic::x86_fma_vfnmadd_ps:
17255   case Intrinsic::x86_fma_vfnmadd_pd:
17256   case Intrinsic::x86_fma_vfnmsub_ps:
17257   case Intrinsic::x86_fma_vfnmsub_pd:
17258   case Intrinsic::x86_fma_vfmaddsub_ps:
17259   case Intrinsic::x86_fma_vfmaddsub_pd:
17260   case Intrinsic::x86_fma_vfmsubadd_ps:
17261   case Intrinsic::x86_fma_vfmsubadd_pd:
17262   case Intrinsic::x86_fma_vfmadd_ps_256:
17263   case Intrinsic::x86_fma_vfmadd_pd_256:
17264   case Intrinsic::x86_fma_vfmsub_ps_256:
17265   case Intrinsic::x86_fma_vfmsub_pd_256:
17266   case Intrinsic::x86_fma_vfnmadd_ps_256:
17267   case Intrinsic::x86_fma_vfnmadd_pd_256:
17268   case Intrinsic::x86_fma_vfnmsub_ps_256:
17269   case Intrinsic::x86_fma_vfnmsub_pd_256:
17270   case Intrinsic::x86_fma_vfmaddsub_ps_256:
17271   case Intrinsic::x86_fma_vfmaddsub_pd_256:
17272   case Intrinsic::x86_fma_vfmsubadd_ps_256:
17273   case Intrinsic::x86_fma_vfmsubadd_pd_256:
17274     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
17275                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
17276   }
17277 }
17278
17279 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17280                               SDValue Src, SDValue Mask, SDValue Base,
17281                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17282                               const X86Subtarget * Subtarget) {
17283   SDLoc dl(Op);
17284   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17285   assert(C && "Invalid scale type");
17286   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17287   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17288                              Index.getSimpleValueType().getVectorNumElements());
17289   SDValue MaskInReg;
17290   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17291   if (MaskC)
17292     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17293   else
17294     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17295   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17296   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17297   SDValue Segment = DAG.getRegister(0, MVT::i32);
17298   if (Src.getOpcode() == ISD::UNDEF)
17299     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
17300   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17301   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17302   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17303   return DAG.getMergeValues(RetOps, dl);
17304 }
17305
17306 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17307                                SDValue Src, SDValue Mask, SDValue Base,
17308                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17309   SDLoc dl(Op);
17310   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17311   assert(C && "Invalid scale type");
17312   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17313   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17314   SDValue Segment = DAG.getRegister(0, MVT::i32);
17315   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17316                              Index.getSimpleValueType().getVectorNumElements());
17317   SDValue MaskInReg;
17318   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17319   if (MaskC)
17320     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17321   else
17322     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17323   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17324   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17325   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17326   return SDValue(Res, 1);
17327 }
17328
17329 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17330                                SDValue Mask, SDValue Base, SDValue Index,
17331                                SDValue ScaleOp, SDValue Chain) {
17332   SDLoc dl(Op);
17333   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17334   assert(C && "Invalid scale type");
17335   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17336   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17337   SDValue Segment = DAG.getRegister(0, MVT::i32);
17338   EVT MaskVT =
17339     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17340   SDValue MaskInReg;
17341   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17342   if (MaskC)
17343     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17344   else
17345     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17346   //SDVTList VTs = DAG.getVTList(MVT::Other);
17347   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17348   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17349   return SDValue(Res, 0);
17350 }
17351
17352 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17353 // read performance monitor counters (x86_rdpmc).
17354 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17355                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17356                               SmallVectorImpl<SDValue> &Results) {
17357   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17358   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17359   SDValue LO, HI;
17360
17361   // The ECX register is used to select the index of the performance counter
17362   // to read.
17363   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17364                                    N->getOperand(2));
17365   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17366
17367   // Reads the content of a 64-bit performance counter and returns it in the
17368   // registers EDX:EAX.
17369   if (Subtarget->is64Bit()) {
17370     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17371     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17372                             LO.getValue(2));
17373   } else {
17374     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17375     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17376                             LO.getValue(2));
17377   }
17378   Chain = HI.getValue(1);
17379
17380   if (Subtarget->is64Bit()) {
17381     // The EAX register is loaded with the low-order 32 bits. The EDX register
17382     // is loaded with the supported high-order bits of the counter.
17383     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17384                               DAG.getConstant(32, MVT::i8));
17385     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17386     Results.push_back(Chain);
17387     return;
17388   }
17389
17390   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17391   SDValue Ops[] = { LO, HI };
17392   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17393   Results.push_back(Pair);
17394   Results.push_back(Chain);
17395 }
17396
17397 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17398 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17399 // also used to custom lower READCYCLECOUNTER nodes.
17400 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17401                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17402                               SmallVectorImpl<SDValue> &Results) {
17403   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17404   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17405   SDValue LO, HI;
17406
17407   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17408   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17409   // and the EAX register is loaded with the low-order 32 bits.
17410   if (Subtarget->is64Bit()) {
17411     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17412     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17413                             LO.getValue(2));
17414   } else {
17415     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17416     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17417                             LO.getValue(2));
17418   }
17419   SDValue Chain = HI.getValue(1);
17420
17421   if (Opcode == X86ISD::RDTSCP_DAG) {
17422     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17423
17424     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17425     // the ECX register. Add 'ecx' explicitly to the chain.
17426     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17427                                      HI.getValue(2));
17428     // Explicitly store the content of ECX at the location passed in input
17429     // to the 'rdtscp' intrinsic.
17430     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17431                          MachinePointerInfo(), false, false, 0);
17432   }
17433
17434   if (Subtarget->is64Bit()) {
17435     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17436     // the EAX register is loaded with the low-order 32 bits.
17437     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17438                               DAG.getConstant(32, MVT::i8));
17439     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17440     Results.push_back(Chain);
17441     return;
17442   }
17443
17444   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17445   SDValue Ops[] = { LO, HI };
17446   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17447   Results.push_back(Pair);
17448   Results.push_back(Chain);
17449 }
17450
17451 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17452                                      SelectionDAG &DAG) {
17453   SmallVector<SDValue, 2> Results;
17454   SDLoc DL(Op);
17455   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17456                           Results);
17457   return DAG.getMergeValues(Results, DL);
17458 }
17459
17460
17461 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17462                                       SelectionDAG &DAG) {
17463   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17464
17465   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17466   if (!IntrData)
17467     return SDValue();
17468
17469   SDLoc dl(Op);
17470   switch(IntrData->Type) {
17471   default:
17472     llvm_unreachable("Unknown Intrinsic Type");
17473     break;
17474   case RDSEED:
17475   case RDRAND: {
17476     // Emit the node with the right value type.
17477     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17478     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17479
17480     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17481     // Otherwise return the value from Rand, which is always 0, casted to i32.
17482     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17483                       DAG.getConstant(1, Op->getValueType(1)),
17484                       DAG.getConstant(X86::COND_B, MVT::i32),
17485                       SDValue(Result.getNode(), 1) };
17486     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17487                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17488                                   Ops);
17489
17490     // Return { result, isValid, chain }.
17491     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17492                        SDValue(Result.getNode(), 2));
17493   }
17494   case GATHER: {
17495   //gather(v1, mask, index, base, scale);
17496     SDValue Chain = Op.getOperand(0);
17497     SDValue Src   = Op.getOperand(2);
17498     SDValue Base  = Op.getOperand(3);
17499     SDValue Index = Op.getOperand(4);
17500     SDValue Mask  = Op.getOperand(5);
17501     SDValue Scale = Op.getOperand(6);
17502     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
17503                           Subtarget);
17504   }
17505   case SCATTER: {
17506   //scatter(base, mask, index, v1, scale);
17507     SDValue Chain = Op.getOperand(0);
17508     SDValue Base  = Op.getOperand(2);
17509     SDValue Mask  = Op.getOperand(3);
17510     SDValue Index = Op.getOperand(4);
17511     SDValue Src   = Op.getOperand(5);
17512     SDValue Scale = Op.getOperand(6);
17513     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
17514   }
17515   case PREFETCH: {
17516     SDValue Hint = Op.getOperand(6);
17517     unsigned HintVal;
17518     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
17519         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
17520       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
17521     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17522     SDValue Chain = Op.getOperand(0);
17523     SDValue Mask  = Op.getOperand(2);
17524     SDValue Index = Op.getOperand(3);
17525     SDValue Base  = Op.getOperand(4);
17526     SDValue Scale = Op.getOperand(5);
17527     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17528   }
17529   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17530   case RDTSC: {
17531     SmallVector<SDValue, 2> Results;
17532     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
17533     return DAG.getMergeValues(Results, dl);
17534   }
17535   // Read Performance Monitoring Counters.
17536   case RDPMC: {
17537     SmallVector<SDValue, 2> Results;
17538     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17539     return DAG.getMergeValues(Results, dl);
17540   }
17541   // XTEST intrinsics.
17542   case XTEST: {
17543     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17544     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17545     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17546                                 DAG.getConstant(X86::COND_NE, MVT::i8),
17547                                 InTrans);
17548     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17549     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17550                        Ret, SDValue(InTrans.getNode(), 1));
17551   }
17552   // ADC/ADCX/SBB
17553   case ADX: {
17554     SmallVector<SDValue, 2> Results;
17555     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17556     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17557     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17558                                 DAG.getConstant(-1, MVT::i8));
17559     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17560                               Op.getOperand(4), GenCF.getValue(1));
17561     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17562                                  Op.getOperand(5), MachinePointerInfo(),
17563                                  false, false, 0);
17564     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17565                                 DAG.getConstant(X86::COND_B, MVT::i8),
17566                                 Res.getValue(1));
17567     Results.push_back(SetCC);
17568     Results.push_back(Store);
17569     return DAG.getMergeValues(Results, dl);
17570   }
17571   case COMPRESS_TO_MEM: {
17572     SDLoc dl(Op);
17573     SDValue Mask = Op.getOperand(4);
17574     SDValue DataToCompress = Op.getOperand(3);
17575     SDValue Addr = Op.getOperand(2);
17576     SDValue Chain = Op.getOperand(0);
17577
17578     if (isAllOnes(Mask)) // return just a store
17579       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17580                           MachinePointerInfo(), false, false, 0);
17581
17582     EVT VT = DataToCompress.getValueType();
17583     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17584                                   VT.getVectorNumElements());
17585     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17586                                      Mask.getValueType().getSizeInBits());
17587     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17588                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17589                                 DAG.getIntPtrConstant(0));
17590
17591     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
17592                                       DataToCompress, DAG.getUNDEF(VT));
17593     return DAG.getStore(Chain, dl, Compressed, Addr,
17594                         MachinePointerInfo(), false, false, 0);
17595   }
17596   case EXPAND_FROM_MEM: {
17597     SDLoc dl(Op);
17598     SDValue Mask = Op.getOperand(4);
17599     SDValue PathThru = Op.getOperand(3);
17600     SDValue Addr = Op.getOperand(2);
17601     SDValue Chain = Op.getOperand(0);
17602     EVT VT = Op.getValueType();
17603
17604     if (isAllOnes(Mask)) // return just a load
17605       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17606                          false, 0);
17607     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17608                                   VT.getVectorNumElements());
17609     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17610                                      Mask.getValueType().getSizeInBits());
17611     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17612                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17613                                 DAG.getIntPtrConstant(0));
17614
17615     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17616                                    false, false, false, 0);
17617
17618     SmallVector<SDValue, 2> Results;
17619     Results.push_back(DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand,
17620                                   PathThru));
17621     Results.push_back(Chain);
17622     return DAG.getMergeValues(Results, dl);
17623   }
17624   }
17625 }
17626
17627 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17628                                            SelectionDAG &DAG) const {
17629   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17630   MFI->setReturnAddressIsTaken(true);
17631
17632   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17633     return SDValue();
17634
17635   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17636   SDLoc dl(Op);
17637   EVT PtrVT = getPointerTy();
17638
17639   if (Depth > 0) {
17640     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17641     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17642         DAG.getSubtarget().getRegisterInfo());
17643     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
17644     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17645                        DAG.getNode(ISD::ADD, dl, PtrVT,
17646                                    FrameAddr, Offset),
17647                        MachinePointerInfo(), false, false, false, 0);
17648   }
17649
17650   // Just load the return address.
17651   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17652   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17653                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17654 }
17655
17656 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17657   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17658   MFI->setFrameAddressIsTaken(true);
17659
17660   EVT VT = Op.getValueType();
17661   SDLoc dl(Op);  // FIXME probably not meaningful
17662   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17663   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17664       DAG.getSubtarget().getRegisterInfo());
17665   unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(
17666       DAG.getMachineFunction());
17667   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17668           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17669          "Invalid Frame Register!");
17670   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17671   while (Depth--)
17672     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17673                             MachinePointerInfo(),
17674                             false, false, false, 0);
17675   return FrameAddr;
17676 }
17677
17678 // FIXME? Maybe this could be a TableGen attribute on some registers and
17679 // this table could be generated automatically from RegInfo.
17680 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
17681                                               EVT VT) const {
17682   unsigned Reg = StringSwitch<unsigned>(RegName)
17683                        .Case("esp", X86::ESP)
17684                        .Case("rsp", X86::RSP)
17685                        .Default(0);
17686   if (Reg)
17687     return Reg;
17688   report_fatal_error("Invalid register name global variable");
17689 }
17690
17691 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17692                                                      SelectionDAG &DAG) const {
17693   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17694       DAG.getSubtarget().getRegisterInfo());
17695   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
17696 }
17697
17698 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17699   SDValue Chain     = Op.getOperand(0);
17700   SDValue Offset    = Op.getOperand(1);
17701   SDValue Handler   = Op.getOperand(2);
17702   SDLoc dl      (Op);
17703
17704   EVT PtrVT = getPointerTy();
17705   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17706       DAG.getSubtarget().getRegisterInfo());
17707   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17708   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17709           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17710          "Invalid Frame Register!");
17711   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17712   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17713
17714   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17715                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
17716   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17717   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17718                        false, false, 0);
17719   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17720
17721   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17722                      DAG.getRegister(StoreAddrReg, PtrVT));
17723 }
17724
17725 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17726                                                SelectionDAG &DAG) const {
17727   SDLoc DL(Op);
17728   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17729                      DAG.getVTList(MVT::i32, MVT::Other),
17730                      Op.getOperand(0), Op.getOperand(1));
17731 }
17732
17733 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17734                                                 SelectionDAG &DAG) const {
17735   SDLoc DL(Op);
17736   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17737                      Op.getOperand(0), Op.getOperand(1));
17738 }
17739
17740 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17741   return Op.getOperand(0);
17742 }
17743
17744 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17745                                                 SelectionDAG &DAG) const {
17746   SDValue Root = Op.getOperand(0);
17747   SDValue Trmp = Op.getOperand(1); // trampoline
17748   SDValue FPtr = Op.getOperand(2); // nested function
17749   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17750   SDLoc dl (Op);
17751
17752   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17753   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
17754
17755   if (Subtarget->is64Bit()) {
17756     SDValue OutChains[6];
17757
17758     // Large code-model.
17759     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17760     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17761
17762     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17763     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17764
17765     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17766
17767     // Load the pointer to the nested function into R11.
17768     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17769     SDValue Addr = Trmp;
17770     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17771                                 Addr, MachinePointerInfo(TrmpAddr),
17772                                 false, false, 0);
17773
17774     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17775                        DAG.getConstant(2, MVT::i64));
17776     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17777                                 MachinePointerInfo(TrmpAddr, 2),
17778                                 false, false, 2);
17779
17780     // Load the 'nest' parameter value into R10.
17781     // R10 is specified in X86CallingConv.td
17782     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17783     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17784                        DAG.getConstant(10, MVT::i64));
17785     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17786                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17787                                 false, false, 0);
17788
17789     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17790                        DAG.getConstant(12, MVT::i64));
17791     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17792                                 MachinePointerInfo(TrmpAddr, 12),
17793                                 false, false, 2);
17794
17795     // Jump to the nested function.
17796     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17797     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17798                        DAG.getConstant(20, MVT::i64));
17799     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17800                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17801                                 false, false, 0);
17802
17803     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17804     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17805                        DAG.getConstant(22, MVT::i64));
17806     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
17807                                 MachinePointerInfo(TrmpAddr, 22),
17808                                 false, false, 0);
17809
17810     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17811   } else {
17812     const Function *Func =
17813       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17814     CallingConv::ID CC = Func->getCallingConv();
17815     unsigned NestReg;
17816
17817     switch (CC) {
17818     default:
17819       llvm_unreachable("Unsupported calling convention");
17820     case CallingConv::C:
17821     case CallingConv::X86_StdCall: {
17822       // Pass 'nest' parameter in ECX.
17823       // Must be kept in sync with X86CallingConv.td
17824       NestReg = X86::ECX;
17825
17826       // Check that ECX wasn't needed by an 'inreg' parameter.
17827       FunctionType *FTy = Func->getFunctionType();
17828       const AttributeSet &Attrs = Func->getAttributes();
17829
17830       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17831         unsigned InRegCount = 0;
17832         unsigned Idx = 1;
17833
17834         for (FunctionType::param_iterator I = FTy->param_begin(),
17835              E = FTy->param_end(); I != E; ++I, ++Idx)
17836           if (Attrs.hasAttribute(Idx, Attribute::InReg))
17837             // FIXME: should only count parameters that are lowered to integers.
17838             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
17839
17840         if (InRegCount > 2) {
17841           report_fatal_error("Nest register in use - reduce number of inreg"
17842                              " parameters!");
17843         }
17844       }
17845       break;
17846     }
17847     case CallingConv::X86_FastCall:
17848     case CallingConv::X86_ThisCall:
17849     case CallingConv::Fast:
17850       // Pass 'nest' parameter in EAX.
17851       // Must be kept in sync with X86CallingConv.td
17852       NestReg = X86::EAX;
17853       break;
17854     }
17855
17856     SDValue OutChains[4];
17857     SDValue Addr, Disp;
17858
17859     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17860                        DAG.getConstant(10, MVT::i32));
17861     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17862
17863     // This is storing the opcode for MOV32ri.
17864     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17865     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17866     OutChains[0] = DAG.getStore(Root, dl,
17867                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
17868                                 Trmp, MachinePointerInfo(TrmpAddr),
17869                                 false, false, 0);
17870
17871     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17872                        DAG.getConstant(1, MVT::i32));
17873     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17874                                 MachinePointerInfo(TrmpAddr, 1),
17875                                 false, false, 1);
17876
17877     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17878     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17879                        DAG.getConstant(5, MVT::i32));
17880     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
17881                                 MachinePointerInfo(TrmpAddr, 5),
17882                                 false, false, 1);
17883
17884     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17885                        DAG.getConstant(6, MVT::i32));
17886     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17887                                 MachinePointerInfo(TrmpAddr, 6),
17888                                 false, false, 1);
17889
17890     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17891   }
17892 }
17893
17894 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17895                                             SelectionDAG &DAG) const {
17896   /*
17897    The rounding mode is in bits 11:10 of FPSR, and has the following
17898    settings:
17899      00 Round to nearest
17900      01 Round to -inf
17901      10 Round to +inf
17902      11 Round to 0
17903
17904   FLT_ROUNDS, on the other hand, expects the following:
17905     -1 Undefined
17906      0 Round to 0
17907      1 Round to nearest
17908      2 Round to +inf
17909      3 Round to -inf
17910
17911   To perform the conversion, we do:
17912     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17913   */
17914
17915   MachineFunction &MF = DAG.getMachineFunction();
17916   const TargetMachine &TM = MF.getTarget();
17917   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
17918   unsigned StackAlignment = TFI.getStackAlignment();
17919   MVT VT = Op.getSimpleValueType();
17920   SDLoc DL(Op);
17921
17922   // Save FP Control Word to stack slot
17923   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17924   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
17925
17926   MachineMemOperand *MMO =
17927    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
17928                            MachineMemOperand::MOStore, 2, 2);
17929
17930   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17931   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17932                                           DAG.getVTList(MVT::Other),
17933                                           Ops, MVT::i16, MMO);
17934
17935   // Load FP Control Word from stack slot
17936   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17937                             MachinePointerInfo(), false, false, false, 0);
17938
17939   // Transform as necessary
17940   SDValue CWD1 =
17941     DAG.getNode(ISD::SRL, DL, MVT::i16,
17942                 DAG.getNode(ISD::AND, DL, MVT::i16,
17943                             CWD, DAG.getConstant(0x800, MVT::i16)),
17944                 DAG.getConstant(11, MVT::i8));
17945   SDValue CWD2 =
17946     DAG.getNode(ISD::SRL, DL, MVT::i16,
17947                 DAG.getNode(ISD::AND, DL, MVT::i16,
17948                             CWD, DAG.getConstant(0x400, MVT::i16)),
17949                 DAG.getConstant(9, MVT::i8));
17950
17951   SDValue RetVal =
17952     DAG.getNode(ISD::AND, DL, MVT::i16,
17953                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17954                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17955                             DAG.getConstant(1, MVT::i16)),
17956                 DAG.getConstant(3, MVT::i16));
17957
17958   return DAG.getNode((VT.getSizeInBits() < 16 ?
17959                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17960 }
17961
17962 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17963   MVT VT = Op.getSimpleValueType();
17964   EVT OpVT = VT;
17965   unsigned NumBits = VT.getSizeInBits();
17966   SDLoc dl(Op);
17967
17968   Op = Op.getOperand(0);
17969   if (VT == MVT::i8) {
17970     // Zero extend to i32 since there is not an i8 bsr.
17971     OpVT = MVT::i32;
17972     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17973   }
17974
17975   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17976   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17977   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17978
17979   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17980   SDValue Ops[] = {
17981     Op,
17982     DAG.getConstant(NumBits+NumBits-1, OpVT),
17983     DAG.getConstant(X86::COND_E, MVT::i8),
17984     Op.getValue(1)
17985   };
17986   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17987
17988   // Finally xor with NumBits-1.
17989   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17990
17991   if (VT == MVT::i8)
17992     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17993   return Op;
17994 }
17995
17996 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17997   MVT VT = Op.getSimpleValueType();
17998   EVT OpVT = VT;
17999   unsigned NumBits = VT.getSizeInBits();
18000   SDLoc dl(Op);
18001
18002   Op = Op.getOperand(0);
18003   if (VT == MVT::i8) {
18004     // Zero extend to i32 since there is not an i8 bsr.
18005     OpVT = MVT::i32;
18006     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18007   }
18008
18009   // Issue a bsr (scan bits in reverse).
18010   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18011   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18012
18013   // And xor with NumBits-1.
18014   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
18015
18016   if (VT == MVT::i8)
18017     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18018   return Op;
18019 }
18020
18021 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18022   MVT VT = Op.getSimpleValueType();
18023   unsigned NumBits = VT.getSizeInBits();
18024   SDLoc dl(Op);
18025   Op = Op.getOperand(0);
18026
18027   // Issue a bsf (scan bits forward) which also sets EFLAGS.
18028   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18029   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
18030
18031   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18032   SDValue Ops[] = {
18033     Op,
18034     DAG.getConstant(NumBits, VT),
18035     DAG.getConstant(X86::COND_E, MVT::i8),
18036     Op.getValue(1)
18037   };
18038   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18039 }
18040
18041 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18042 // ones, and then concatenate the result back.
18043 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18044   MVT VT = Op.getSimpleValueType();
18045
18046   assert(VT.is256BitVector() && VT.isInteger() &&
18047          "Unsupported value type for operation");
18048
18049   unsigned NumElems = VT.getVectorNumElements();
18050   SDLoc dl(Op);
18051
18052   // Extract the LHS vectors
18053   SDValue LHS = Op.getOperand(0);
18054   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18055   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18056
18057   // Extract the RHS vectors
18058   SDValue RHS = Op.getOperand(1);
18059   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18060   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18061
18062   MVT EltVT = VT.getVectorElementType();
18063   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18064
18065   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18066                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18067                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18068 }
18069
18070 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18071   assert(Op.getSimpleValueType().is256BitVector() &&
18072          Op.getSimpleValueType().isInteger() &&
18073          "Only handle AVX 256-bit vector integer operation");
18074   return Lower256IntArith(Op, DAG);
18075 }
18076
18077 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18078   assert(Op.getSimpleValueType().is256BitVector() &&
18079          Op.getSimpleValueType().isInteger() &&
18080          "Only handle AVX 256-bit vector integer operation");
18081   return Lower256IntArith(Op, DAG);
18082 }
18083
18084 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18085                         SelectionDAG &DAG) {
18086   SDLoc dl(Op);
18087   MVT VT = Op.getSimpleValueType();
18088
18089   // Decompose 256-bit ops into smaller 128-bit ops.
18090   if (VT.is256BitVector() && !Subtarget->hasInt256())
18091     return Lower256IntArith(Op, DAG);
18092
18093   SDValue A = Op.getOperand(0);
18094   SDValue B = Op.getOperand(1);
18095
18096   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18097   if (VT == MVT::v4i32) {
18098     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18099            "Should not custom lower when pmuldq is available!");
18100
18101     // Extract the odd parts.
18102     static const int UnpackMask[] = { 1, -1, 3, -1 };
18103     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18104     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18105
18106     // Multiply the even parts.
18107     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18108     // Now multiply odd parts.
18109     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18110
18111     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
18112     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
18113
18114     // Merge the two vectors back together with a shuffle. This expands into 2
18115     // shuffles.
18116     static const int ShufMask[] = { 0, 4, 2, 6 };
18117     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18118   }
18119
18120   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18121          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18122
18123   //  Ahi = psrlqi(a, 32);
18124   //  Bhi = psrlqi(b, 32);
18125   //
18126   //  AloBlo = pmuludq(a, b);
18127   //  AloBhi = pmuludq(a, Bhi);
18128   //  AhiBlo = pmuludq(Ahi, b);
18129
18130   //  AloBhi = psllqi(AloBhi, 32);
18131   //  AhiBlo = psllqi(AhiBlo, 32);
18132   //  return AloBlo + AloBhi + AhiBlo;
18133
18134   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18135   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18136
18137   // Bit cast to 32-bit vectors for MULUDQ
18138   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18139                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18140   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
18141   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
18142   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
18143   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
18144
18145   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18146   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18147   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18148
18149   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18150   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18151
18152   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18153   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18154 }
18155
18156 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18157   assert(Subtarget->isTargetWin64() && "Unexpected target");
18158   EVT VT = Op.getValueType();
18159   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18160          "Unexpected return type for lowering");
18161
18162   RTLIB::Libcall LC;
18163   bool isSigned;
18164   switch (Op->getOpcode()) {
18165   default: llvm_unreachable("Unexpected request for libcall!");
18166   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18167   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18168   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18169   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18170   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18171   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18172   }
18173
18174   SDLoc dl(Op);
18175   SDValue InChain = DAG.getEntryNode();
18176
18177   TargetLowering::ArgListTy Args;
18178   TargetLowering::ArgListEntry Entry;
18179   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18180     EVT ArgVT = Op->getOperand(i).getValueType();
18181     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18182            "Unexpected argument type for lowering");
18183     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18184     Entry.Node = StackPtr;
18185     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18186                            false, false, 16);
18187     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18188     Entry.Ty = PointerType::get(ArgTy,0);
18189     Entry.isSExt = false;
18190     Entry.isZExt = false;
18191     Args.push_back(Entry);
18192   }
18193
18194   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18195                                          getPointerTy());
18196
18197   TargetLowering::CallLoweringInfo CLI(DAG);
18198   CLI.setDebugLoc(dl).setChain(InChain)
18199     .setCallee(getLibcallCallingConv(LC),
18200                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18201                Callee, std::move(Args), 0)
18202     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18203
18204   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18205   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
18206 }
18207
18208 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18209                              SelectionDAG &DAG) {
18210   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18211   EVT VT = Op0.getValueType();
18212   SDLoc dl(Op);
18213
18214   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18215          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18216
18217   // PMULxD operations multiply each even value (starting at 0) of LHS with
18218   // the related value of RHS and produce a widen result.
18219   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18220   // => <2 x i64> <ae|cg>
18221   //
18222   // In other word, to have all the results, we need to perform two PMULxD:
18223   // 1. one with the even values.
18224   // 2. one with the odd values.
18225   // To achieve #2, with need to place the odd values at an even position.
18226   //
18227   // Place the odd value at an even position (basically, shift all values 1
18228   // step to the left):
18229   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18230   // <a|b|c|d> => <b|undef|d|undef>
18231   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18232   // <e|f|g|h> => <f|undef|h|undef>
18233   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18234
18235   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18236   // ints.
18237   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18238   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18239   unsigned Opcode =
18240       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18241   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18242   // => <2 x i64> <ae|cg>
18243   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
18244                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18245   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18246   // => <2 x i64> <bf|dh>
18247   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
18248                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18249
18250   // Shuffle it back into the right order.
18251   SDValue Highs, Lows;
18252   if (VT == MVT::v8i32) {
18253     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18254     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18255     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18256     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18257   } else {
18258     const int HighMask[] = {1, 5, 3, 7};
18259     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18260     const int LowMask[] = {0, 4, 2, 6};
18261     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18262   }
18263
18264   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18265   // unsigned multiply.
18266   if (IsSigned && !Subtarget->hasSSE41()) {
18267     SDValue ShAmt =
18268         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
18269     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18270                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18271     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18272                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18273
18274     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18275     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18276   }
18277
18278   // The first result of MUL_LOHI is actually the low value, followed by the
18279   // high value.
18280   SDValue Ops[] = {Lows, Highs};
18281   return DAG.getMergeValues(Ops, dl);
18282 }
18283
18284 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18285                                          const X86Subtarget *Subtarget) {
18286   MVT VT = Op.getSimpleValueType();
18287   SDLoc dl(Op);
18288   SDValue R = Op.getOperand(0);
18289   SDValue Amt = Op.getOperand(1);
18290
18291   // Optimize shl/srl/sra with constant shift amount.
18292   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18293     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18294       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18295
18296       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
18297           (Subtarget->hasInt256() &&
18298            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18299           (Subtarget->hasAVX512() &&
18300            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18301         if (Op.getOpcode() == ISD::SHL)
18302           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18303                                             DAG);
18304         if (Op.getOpcode() == ISD::SRL)
18305           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18306                                             DAG);
18307         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
18308           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18309                                             DAG);
18310       }
18311
18312       if (VT == MVT::v16i8) {
18313         if (Op.getOpcode() == ISD::SHL) {
18314           // Make a large shift.
18315           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18316                                                    MVT::v8i16, R, ShiftAmt,
18317                                                    DAG);
18318           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18319           // Zero out the rightmost bits.
18320           SmallVector<SDValue, 16> V(16,
18321                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18322                                                      MVT::i8));
18323           return DAG.getNode(ISD::AND, dl, VT, SHL,
18324                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18325         }
18326         if (Op.getOpcode() == ISD::SRL) {
18327           // Make a large shift.
18328           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18329                                                    MVT::v8i16, R, ShiftAmt,
18330                                                    DAG);
18331           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18332           // Zero out the leftmost bits.
18333           SmallVector<SDValue, 16> V(16,
18334                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18335                                                      MVT::i8));
18336           return DAG.getNode(ISD::AND, dl, VT, SRL,
18337                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18338         }
18339         if (Op.getOpcode() == ISD::SRA) {
18340           if (ShiftAmt == 7) {
18341             // R s>> 7  ===  R s< 0
18342             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18343             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18344           }
18345
18346           // R s>> a === ((R u>> a) ^ m) - m
18347           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18348           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
18349                                                          MVT::i8));
18350           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18351           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18352           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18353           return Res;
18354         }
18355         llvm_unreachable("Unknown shift opcode.");
18356       }
18357
18358       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
18359         if (Op.getOpcode() == ISD::SHL) {
18360           // Make a large shift.
18361           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18362                                                    MVT::v16i16, R, ShiftAmt,
18363                                                    DAG);
18364           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18365           // Zero out the rightmost bits.
18366           SmallVector<SDValue, 32> V(32,
18367                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18368                                                      MVT::i8));
18369           return DAG.getNode(ISD::AND, dl, VT, SHL,
18370                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18371         }
18372         if (Op.getOpcode() == ISD::SRL) {
18373           // Make a large shift.
18374           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18375                                                    MVT::v16i16, R, ShiftAmt,
18376                                                    DAG);
18377           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18378           // Zero out the leftmost bits.
18379           SmallVector<SDValue, 32> V(32,
18380                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18381                                                      MVT::i8));
18382           return DAG.getNode(ISD::AND, dl, VT, SRL,
18383                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18384         }
18385         if (Op.getOpcode() == ISD::SRA) {
18386           if (ShiftAmt == 7) {
18387             // R s>> 7  ===  R s< 0
18388             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18389             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18390           }
18391
18392           // R s>> a === ((R u>> a) ^ m) - m
18393           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18394           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
18395                                                          MVT::i8));
18396           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18397           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18398           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18399           return Res;
18400         }
18401         llvm_unreachable("Unknown shift opcode.");
18402       }
18403     }
18404   }
18405
18406   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18407   if (!Subtarget->is64Bit() &&
18408       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18409       Amt.getOpcode() == ISD::BITCAST &&
18410       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18411     Amt = Amt.getOperand(0);
18412     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18413                      VT.getVectorNumElements();
18414     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18415     uint64_t ShiftAmt = 0;
18416     for (unsigned i = 0; i != Ratio; ++i) {
18417       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
18418       if (!C)
18419         return SDValue();
18420       // 6 == Log2(64)
18421       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18422     }
18423     // Check remaining shift amounts.
18424     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18425       uint64_t ShAmt = 0;
18426       for (unsigned j = 0; j != Ratio; ++j) {
18427         ConstantSDNode *C =
18428           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18429         if (!C)
18430           return SDValue();
18431         // 6 == Log2(64)
18432         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18433       }
18434       if (ShAmt != ShiftAmt)
18435         return SDValue();
18436     }
18437     switch (Op.getOpcode()) {
18438     default:
18439       llvm_unreachable("Unknown shift opcode!");
18440     case ISD::SHL:
18441       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18442                                         DAG);
18443     case ISD::SRL:
18444       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18445                                         DAG);
18446     case ISD::SRA:
18447       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18448                                         DAG);
18449     }
18450   }
18451
18452   return SDValue();
18453 }
18454
18455 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18456                                         const X86Subtarget* Subtarget) {
18457   MVT VT = Op.getSimpleValueType();
18458   SDLoc dl(Op);
18459   SDValue R = Op.getOperand(0);
18460   SDValue Amt = Op.getOperand(1);
18461
18462   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
18463       VT == MVT::v4i32 || VT == MVT::v8i16 ||
18464       (Subtarget->hasInt256() &&
18465        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
18466         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18467        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18468     SDValue BaseShAmt;
18469     EVT EltVT = VT.getVectorElementType();
18470
18471     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18472       // Check if this build_vector node is doing a splat.
18473       // If so, then set BaseShAmt equal to the splat value.
18474       BaseShAmt = BV->getSplatValue();
18475       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18476         BaseShAmt = SDValue();
18477     } else {
18478       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18479         Amt = Amt.getOperand(0);
18480
18481       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18482       if (SVN && SVN->isSplat()) {
18483         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18484         SDValue InVec = Amt.getOperand(0);
18485         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18486           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18487                  "Unexpected shuffle index found!");
18488           BaseShAmt = InVec.getOperand(SplatIdx);
18489         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18490            if (ConstantSDNode *C =
18491                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18492              if (C->getZExtValue() == SplatIdx)
18493                BaseShAmt = InVec.getOperand(1);
18494            }
18495         }
18496
18497         if (!BaseShAmt)
18498           // Avoid introducing an extract element from a shuffle.
18499           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18500                                     DAG.getIntPtrConstant(SplatIdx));
18501       }
18502     }
18503
18504     if (BaseShAmt.getNode()) {
18505       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18506       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18507         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18508       else if (EltVT.bitsLT(MVT::i32))
18509         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18510
18511       switch (Op.getOpcode()) {
18512       default:
18513         llvm_unreachable("Unknown shift opcode!");
18514       case ISD::SHL:
18515         switch (VT.SimpleTy) {
18516         default: return SDValue();
18517         case MVT::v2i64:
18518         case MVT::v4i32:
18519         case MVT::v8i16:
18520         case MVT::v4i64:
18521         case MVT::v8i32:
18522         case MVT::v16i16:
18523         case MVT::v16i32:
18524         case MVT::v8i64:
18525           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
18526         }
18527       case ISD::SRA:
18528         switch (VT.SimpleTy) {
18529         default: return SDValue();
18530         case MVT::v4i32:
18531         case MVT::v8i16:
18532         case MVT::v8i32:
18533         case MVT::v16i16:
18534         case MVT::v16i32:
18535         case MVT::v8i64:
18536           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
18537         }
18538       case ISD::SRL:
18539         switch (VT.SimpleTy) {
18540         default: return SDValue();
18541         case MVT::v2i64:
18542         case MVT::v4i32:
18543         case MVT::v8i16:
18544         case MVT::v4i64:
18545         case MVT::v8i32:
18546         case MVT::v16i16:
18547         case MVT::v16i32:
18548         case MVT::v8i64:
18549           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
18550         }
18551       }
18552     }
18553   }
18554
18555   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18556   if (!Subtarget->is64Bit() &&
18557       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
18558       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
18559       Amt.getOpcode() == ISD::BITCAST &&
18560       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18561     Amt = Amt.getOperand(0);
18562     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18563                      VT.getVectorNumElements();
18564     std::vector<SDValue> Vals(Ratio);
18565     for (unsigned i = 0; i != Ratio; ++i)
18566       Vals[i] = Amt.getOperand(i);
18567     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18568       for (unsigned j = 0; j != Ratio; ++j)
18569         if (Vals[j] != Amt.getOperand(i + j))
18570           return SDValue();
18571     }
18572     switch (Op.getOpcode()) {
18573     default:
18574       llvm_unreachable("Unknown shift opcode!");
18575     case ISD::SHL:
18576       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
18577     case ISD::SRL:
18578       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
18579     case ISD::SRA:
18580       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
18581     }
18582   }
18583
18584   return SDValue();
18585 }
18586
18587 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18588                           SelectionDAG &DAG) {
18589   MVT VT = Op.getSimpleValueType();
18590   SDLoc dl(Op);
18591   SDValue R = Op.getOperand(0);
18592   SDValue Amt = Op.getOperand(1);
18593   SDValue V;
18594
18595   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18596   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18597
18598   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
18599   if (V.getNode())
18600     return V;
18601
18602   V = LowerScalarVariableShift(Op, DAG, Subtarget);
18603   if (V.getNode())
18604       return V;
18605
18606   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
18607     return Op;
18608   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
18609   if (Subtarget->hasInt256()) {
18610     if (Op.getOpcode() == ISD::SRL &&
18611         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18612          VT == MVT::v4i64 || VT == MVT::v8i32))
18613       return Op;
18614     if (Op.getOpcode() == ISD::SHL &&
18615         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18616          VT == MVT::v4i64 || VT == MVT::v8i32))
18617       return Op;
18618     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
18619       return Op;
18620   }
18621
18622   // If possible, lower this packed shift into a vector multiply instead of
18623   // expanding it into a sequence of scalar shifts.
18624   // Do this only if the vector shift count is a constant build_vector.
18625   if (Op.getOpcode() == ISD::SHL &&
18626       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18627        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18628       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18629     SmallVector<SDValue, 8> Elts;
18630     EVT SVT = VT.getScalarType();
18631     unsigned SVTBits = SVT.getSizeInBits();
18632     const APInt &One = APInt(SVTBits, 1);
18633     unsigned NumElems = VT.getVectorNumElements();
18634
18635     for (unsigned i=0; i !=NumElems; ++i) {
18636       SDValue Op = Amt->getOperand(i);
18637       if (Op->getOpcode() == ISD::UNDEF) {
18638         Elts.push_back(Op);
18639         continue;
18640       }
18641
18642       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18643       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18644       uint64_t ShAmt = C.getZExtValue();
18645       if (ShAmt >= SVTBits) {
18646         Elts.push_back(DAG.getUNDEF(SVT));
18647         continue;
18648       }
18649       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
18650     }
18651     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18652     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18653   }
18654
18655   // Lower SHL with variable shift amount.
18656   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18657     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
18658
18659     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
18660     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
18661     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18662     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18663   }
18664
18665   // If possible, lower this shift as a sequence of two shifts by
18666   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18667   // Example:
18668   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18669   //
18670   // Could be rewritten as:
18671   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18672   //
18673   // The advantage is that the two shifts from the example would be
18674   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18675   // the vector shift into four scalar shifts plus four pairs of vector
18676   // insert/extract.
18677   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18678       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18679     unsigned TargetOpcode = X86ISD::MOVSS;
18680     bool CanBeSimplified;
18681     // The splat value for the first packed shift (the 'X' from the example).
18682     SDValue Amt1 = Amt->getOperand(0);
18683     // The splat value for the second packed shift (the 'Y' from the example).
18684     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18685                                         Amt->getOperand(2);
18686
18687     // See if it is possible to replace this node with a sequence of
18688     // two shifts followed by a MOVSS/MOVSD
18689     if (VT == MVT::v4i32) {
18690       // Check if it is legal to use a MOVSS.
18691       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18692                         Amt2 == Amt->getOperand(3);
18693       if (!CanBeSimplified) {
18694         // Otherwise, check if we can still simplify this node using a MOVSD.
18695         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18696                           Amt->getOperand(2) == Amt->getOperand(3);
18697         TargetOpcode = X86ISD::MOVSD;
18698         Amt2 = Amt->getOperand(2);
18699       }
18700     } else {
18701       // Do similar checks for the case where the machine value type
18702       // is MVT::v8i16.
18703       CanBeSimplified = Amt1 == Amt->getOperand(1);
18704       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18705         CanBeSimplified = Amt2 == Amt->getOperand(i);
18706
18707       if (!CanBeSimplified) {
18708         TargetOpcode = X86ISD::MOVSD;
18709         CanBeSimplified = true;
18710         Amt2 = Amt->getOperand(4);
18711         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18712           CanBeSimplified = Amt1 == Amt->getOperand(i);
18713         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18714           CanBeSimplified = Amt2 == Amt->getOperand(j);
18715       }
18716     }
18717
18718     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18719         isa<ConstantSDNode>(Amt2)) {
18720       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18721       EVT CastVT = MVT::v4i32;
18722       SDValue Splat1 =
18723         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
18724       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18725       SDValue Splat2 =
18726         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
18727       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18728       if (TargetOpcode == X86ISD::MOVSD)
18729         CastVT = MVT::v2i64;
18730       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
18731       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
18732       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18733                                             BitCast1, DAG);
18734       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
18735     }
18736   }
18737
18738   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
18739     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
18740
18741     // a = a << 5;
18742     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
18743     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
18744
18745     // Turn 'a' into a mask suitable for VSELECT
18746     SDValue VSelM = DAG.getConstant(0x80, VT);
18747     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18748     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18749
18750     SDValue CM1 = DAG.getConstant(0x0f, VT);
18751     SDValue CM2 = DAG.getConstant(0x3f, VT);
18752
18753     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
18754     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
18755     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
18756     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18757     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18758
18759     // a += a
18760     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18761     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18762     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18763
18764     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
18765     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
18766     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
18767     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18768     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18769
18770     // a += a
18771     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18772     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18773     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18774
18775     // return VSELECT(r, r+r, a);
18776     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
18777                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
18778     return R;
18779   }
18780
18781   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18782   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18783   // solution better.
18784   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18785     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
18786     unsigned ExtOpc =
18787         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18788     R = DAG.getNode(ExtOpc, dl, NewVT, R);
18789     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
18790     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18791                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
18792     }
18793
18794   // Decompose 256-bit shifts into smaller 128-bit shifts.
18795   if (VT.is256BitVector()) {
18796     unsigned NumElems = VT.getVectorNumElements();
18797     MVT EltVT = VT.getVectorElementType();
18798     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18799
18800     // Extract the two vectors
18801     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18802     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18803
18804     // Recreate the shift amount vectors
18805     SDValue Amt1, Amt2;
18806     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18807       // Constant shift amount
18808       SmallVector<SDValue, 4> Amt1Csts;
18809       SmallVector<SDValue, 4> Amt2Csts;
18810       for (unsigned i = 0; i != NumElems/2; ++i)
18811         Amt1Csts.push_back(Amt->getOperand(i));
18812       for (unsigned i = NumElems/2; i != NumElems; ++i)
18813         Amt2Csts.push_back(Amt->getOperand(i));
18814
18815       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18816       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18817     } else {
18818       // Variable shift amount
18819       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18820       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18821     }
18822
18823     // Issue new vector shifts for the smaller types
18824     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18825     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18826
18827     // Concatenate the result back
18828     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18829   }
18830
18831   return SDValue();
18832 }
18833
18834 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18835   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18836   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18837   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18838   // has only one use.
18839   SDNode *N = Op.getNode();
18840   SDValue LHS = N->getOperand(0);
18841   SDValue RHS = N->getOperand(1);
18842   unsigned BaseOp = 0;
18843   unsigned Cond = 0;
18844   SDLoc DL(Op);
18845   switch (Op.getOpcode()) {
18846   default: llvm_unreachable("Unknown ovf instruction!");
18847   case ISD::SADDO:
18848     // A subtract of one will be selected as a INC. Note that INC doesn't
18849     // set CF, so we can't do this for UADDO.
18850     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18851       if (C->isOne()) {
18852         BaseOp = X86ISD::INC;
18853         Cond = X86::COND_O;
18854         break;
18855       }
18856     BaseOp = X86ISD::ADD;
18857     Cond = X86::COND_O;
18858     break;
18859   case ISD::UADDO:
18860     BaseOp = X86ISD::ADD;
18861     Cond = X86::COND_B;
18862     break;
18863   case ISD::SSUBO:
18864     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18865     // set CF, so we can't do this for USUBO.
18866     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18867       if (C->isOne()) {
18868         BaseOp = X86ISD::DEC;
18869         Cond = X86::COND_O;
18870         break;
18871       }
18872     BaseOp = X86ISD::SUB;
18873     Cond = X86::COND_O;
18874     break;
18875   case ISD::USUBO:
18876     BaseOp = X86ISD::SUB;
18877     Cond = X86::COND_B;
18878     break;
18879   case ISD::SMULO:
18880     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18881     Cond = X86::COND_O;
18882     break;
18883   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18884     if (N->getValueType(0) == MVT::i8) {
18885       BaseOp = X86ISD::UMUL8;
18886       Cond = X86::COND_O;
18887       break;
18888     }
18889     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18890                                  MVT::i32);
18891     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18892
18893     SDValue SetCC =
18894       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18895                   DAG.getConstant(X86::COND_O, MVT::i32),
18896                   SDValue(Sum.getNode(), 2));
18897
18898     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18899   }
18900   }
18901
18902   // Also sets EFLAGS.
18903   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18904   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18905
18906   SDValue SetCC =
18907     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18908                 DAG.getConstant(Cond, MVT::i32),
18909                 SDValue(Sum.getNode(), 1));
18910
18911   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18912 }
18913
18914 // Sign extension of the low part of vector elements. This may be used either
18915 // when sign extend instructions are not available or if the vector element
18916 // sizes already match the sign-extended size. If the vector elements are in
18917 // their pre-extended size and sign extend instructions are available, that will
18918 // be handled by LowerSIGN_EXTEND.
18919 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
18920                                                   SelectionDAG &DAG) const {
18921   SDLoc dl(Op);
18922   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
18923   MVT VT = Op.getSimpleValueType();
18924
18925   if (!Subtarget->hasSSE2() || !VT.isVector())
18926     return SDValue();
18927
18928   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
18929                       ExtraVT.getScalarType().getSizeInBits();
18930
18931   switch (VT.SimpleTy) {
18932     default: return SDValue();
18933     case MVT::v8i32:
18934     case MVT::v16i16:
18935       if (!Subtarget->hasFp256())
18936         return SDValue();
18937       if (!Subtarget->hasInt256()) {
18938         // needs to be split
18939         unsigned NumElems = VT.getVectorNumElements();
18940
18941         // Extract the LHS vectors
18942         SDValue LHS = Op.getOperand(0);
18943         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18944         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18945
18946         MVT EltVT = VT.getVectorElementType();
18947         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18948
18949         EVT ExtraEltVT = ExtraVT.getVectorElementType();
18950         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
18951         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
18952                                    ExtraNumElems/2);
18953         SDValue Extra = DAG.getValueType(ExtraVT);
18954
18955         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
18956         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
18957
18958         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
18959       }
18960       // fall through
18961     case MVT::v4i32:
18962     case MVT::v8i16: {
18963       SDValue Op0 = Op.getOperand(0);
18964
18965       // This is a sign extension of some low part of vector elements without
18966       // changing the size of the vector elements themselves:
18967       // Shift-Left + Shift-Right-Algebraic.
18968       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
18969                                                BitsDiff, DAG);
18970       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
18971                                         DAG);
18972     }
18973   }
18974 }
18975
18976 /// Returns true if the operand type is exactly twice the native width, and
18977 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18978 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18979 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18980 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
18981   const X86Subtarget &Subtarget =
18982       getTargetMachine().getSubtarget<X86Subtarget>();
18983   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18984
18985   if (OpWidth == 64)
18986     return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18987   else if (OpWidth == 128)
18988     return Subtarget.hasCmpxchg16b();
18989   else
18990     return false;
18991 }
18992
18993 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18994   return needsCmpXchgNb(SI->getValueOperand()->getType());
18995 }
18996
18997 // Note: this turns large loads into lock cmpxchg8b/16b.
18998 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18999 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19000   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19001   return needsCmpXchgNb(PTy->getElementType());
19002 }
19003
19004 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19005   const X86Subtarget &Subtarget =
19006       getTargetMachine().getSubtarget<X86Subtarget>();
19007   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
19008   const Type *MemType = AI->getType();
19009
19010   // If the operand is too big, we must see if cmpxchg8/16b is available
19011   // and default to library calls otherwise.
19012   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19013     return needsCmpXchgNb(MemType);
19014
19015   AtomicRMWInst::BinOp Op = AI->getOperation();
19016   switch (Op) {
19017   default:
19018     llvm_unreachable("Unknown atomic operation");
19019   case AtomicRMWInst::Xchg:
19020   case AtomicRMWInst::Add:
19021   case AtomicRMWInst::Sub:
19022     // It's better to use xadd, xsub or xchg for these in all cases.
19023     return false;
19024   case AtomicRMWInst::Or:
19025   case AtomicRMWInst::And:
19026   case AtomicRMWInst::Xor:
19027     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19028     // prefix to a normal instruction for these operations.
19029     return !AI->use_empty();
19030   case AtomicRMWInst::Nand:
19031   case AtomicRMWInst::Max:
19032   case AtomicRMWInst::Min:
19033   case AtomicRMWInst::UMax:
19034   case AtomicRMWInst::UMin:
19035     // These always require a non-trivial set of data operations on x86. We must
19036     // use a cmpxchg loop.
19037     return true;
19038   }
19039 }
19040
19041 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19042   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19043   // no-sse2). There isn't any reason to disable it if the target processor
19044   // supports it.
19045   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19046 }
19047
19048 LoadInst *
19049 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19050   const X86Subtarget &Subtarget =
19051       getTargetMachine().getSubtarget<X86Subtarget>();
19052   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
19053   const Type *MemType = AI->getType();
19054   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19055   // there is no benefit in turning such RMWs into loads, and it is actually
19056   // harmful as it introduces a mfence.
19057   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19058     return nullptr;
19059
19060   auto Builder = IRBuilder<>(AI);
19061   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19062   auto SynchScope = AI->getSynchScope();
19063   // We must restrict the ordering to avoid generating loads with Release or
19064   // ReleaseAcquire orderings.
19065   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19066   auto Ptr = AI->getPointerOperand();
19067
19068   // Before the load we need a fence. Here is an example lifted from
19069   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19070   // is required:
19071   // Thread 0:
19072   //   x.store(1, relaxed);
19073   //   r1 = y.fetch_add(0, release);
19074   // Thread 1:
19075   //   y.fetch_add(42, acquire);
19076   //   r2 = x.load(relaxed);
19077   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19078   // lowered to just a load without a fence. A mfence flushes the store buffer,
19079   // making the optimization clearly correct.
19080   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19081   // otherwise, we might be able to be more agressive on relaxed idempotent
19082   // rmw. In practice, they do not look useful, so we don't try to be
19083   // especially clever.
19084   if (SynchScope == SingleThread) {
19085     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19086     // the IR level, so we must wrap it in an intrinsic.
19087     return nullptr;
19088   } else if (hasMFENCE(Subtarget)) {
19089     Function *MFence = llvm::Intrinsic::getDeclaration(M,
19090             Intrinsic::x86_sse2_mfence);
19091     Builder.CreateCall(MFence);
19092   } else {
19093     // FIXME: it might make sense to use a locked operation here but on a
19094     // different cache-line to prevent cache-line bouncing. In practice it
19095     // is probably a small win, and x86 processors without mfence are rare
19096     // enough that we do not bother.
19097     return nullptr;
19098   }
19099
19100   // Finally we can emit the atomic load.
19101   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19102           AI->getType()->getPrimitiveSizeInBits());
19103   Loaded->setAtomic(Order, SynchScope);
19104   AI->replaceAllUsesWith(Loaded);
19105   AI->eraseFromParent();
19106   return Loaded;
19107 }
19108
19109 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19110                                  SelectionDAG &DAG) {
19111   SDLoc dl(Op);
19112   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19113     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19114   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19115     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19116
19117   // The only fence that needs an instruction is a sequentially-consistent
19118   // cross-thread fence.
19119   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19120     if (hasMFENCE(*Subtarget))
19121       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19122
19123     SDValue Chain = Op.getOperand(0);
19124     SDValue Zero = DAG.getConstant(0, MVT::i32);
19125     SDValue Ops[] = {
19126       DAG.getRegister(X86::ESP, MVT::i32), // Base
19127       DAG.getTargetConstant(1, MVT::i8),   // Scale
19128       DAG.getRegister(0, MVT::i32),        // Index
19129       DAG.getTargetConstant(0, MVT::i32),  // Disp
19130       DAG.getRegister(0, MVT::i32),        // Segment.
19131       Zero,
19132       Chain
19133     };
19134     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19135     return SDValue(Res, 0);
19136   }
19137
19138   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19139   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19140 }
19141
19142 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19143                              SelectionDAG &DAG) {
19144   MVT T = Op.getSimpleValueType();
19145   SDLoc DL(Op);
19146   unsigned Reg = 0;
19147   unsigned size = 0;
19148   switch(T.SimpleTy) {
19149   default: llvm_unreachable("Invalid value type!");
19150   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19151   case MVT::i16: Reg = X86::AX;  size = 2; break;
19152   case MVT::i32: Reg = X86::EAX; size = 4; break;
19153   case MVT::i64:
19154     assert(Subtarget->is64Bit() && "Node not type legal!");
19155     Reg = X86::RAX; size = 8;
19156     break;
19157   }
19158   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19159                                   Op.getOperand(2), SDValue());
19160   SDValue Ops[] = { cpIn.getValue(0),
19161                     Op.getOperand(1),
19162                     Op.getOperand(3),
19163                     DAG.getTargetConstant(size, MVT::i8),
19164                     cpIn.getValue(1) };
19165   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19166   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19167   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19168                                            Ops, T, MMO);
19169
19170   SDValue cpOut =
19171     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19172   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19173                                       MVT::i32, cpOut.getValue(2));
19174   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19175                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19176
19177   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19178   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19179   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19180   return SDValue();
19181 }
19182
19183 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19184                             SelectionDAG &DAG) {
19185   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19186   MVT DstVT = Op.getSimpleValueType();
19187
19188   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19189     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19190     if (DstVT != MVT::f64)
19191       // This conversion needs to be expanded.
19192       return SDValue();
19193
19194     SDValue InVec = Op->getOperand(0);
19195     SDLoc dl(Op);
19196     unsigned NumElts = SrcVT.getVectorNumElements();
19197     EVT SVT = SrcVT.getVectorElementType();
19198
19199     // Widen the vector in input in the case of MVT::v2i32.
19200     // Example: from MVT::v2i32 to MVT::v4i32.
19201     SmallVector<SDValue, 16> Elts;
19202     for (unsigned i = 0, e = NumElts; i != e; ++i)
19203       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19204                                  DAG.getIntPtrConstant(i)));
19205
19206     // Explicitly mark the extra elements as Undef.
19207     SDValue Undef = DAG.getUNDEF(SVT);
19208     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
19209       Elts.push_back(Undef);
19210
19211     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19212     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19213     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
19214     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19215                        DAG.getIntPtrConstant(0));
19216   }
19217
19218   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19219          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19220   assert((DstVT == MVT::i64 ||
19221           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19222          "Unexpected custom BITCAST");
19223   // i64 <=> MMX conversions are Legal.
19224   if (SrcVT==MVT::i64 && DstVT.isVector())
19225     return Op;
19226   if (DstVT==MVT::i64 && SrcVT.isVector())
19227     return Op;
19228   // MMX <=> MMX conversions are Legal.
19229   if (SrcVT.isVector() && DstVT.isVector())
19230     return Op;
19231   // All other conversions need to be expanded.
19232   return SDValue();
19233 }
19234
19235 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19236                           SelectionDAG &DAG) {
19237   SDNode *Node = Op.getNode();
19238   SDLoc dl(Node);
19239
19240   Op = Op.getOperand(0);
19241   EVT VT = Op.getValueType();
19242   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19243          "CTPOP lowering only implemented for 128/256-bit wide vector types");
19244
19245   unsigned NumElts = VT.getVectorNumElements();
19246   EVT EltVT = VT.getVectorElementType();
19247   unsigned Len = EltVT.getSizeInBits();
19248
19249   // This is the vectorized version of the "best" algorithm from
19250   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19251   // with a minor tweak to use a series of adds + shifts instead of vector
19252   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
19253   //
19254   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
19255   //  v8i32 => Always profitable
19256   //
19257   // FIXME: There a couple of possible improvements:
19258   //
19259   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
19260   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
19261   //
19262   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
19263          "CTPOP not implemented for this vector element type.");
19264
19265   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
19266   // extra legalization.
19267   bool NeedsBitcast = EltVT == MVT::i32;
19268   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
19269
19270   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
19271   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
19272   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
19273
19274   // v = v - ((v >> 1) & 0x55555555...)
19275   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
19276   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
19277   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
19278   if (NeedsBitcast)
19279     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
19280
19281   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
19282   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
19283   if (NeedsBitcast)
19284     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
19285
19286   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
19287   if (VT != And.getValueType())
19288     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19289   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
19290
19291   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19292   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
19293   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
19294   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
19295   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
19296
19297   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
19298   if (NeedsBitcast) {
19299     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
19300     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
19301     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
19302   }
19303
19304   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
19305   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
19306   if (VT != AndRHS.getValueType()) {
19307     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
19308     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
19309   }
19310   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
19311
19312   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19313   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
19314   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
19315   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
19316   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
19317
19318   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
19319   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
19320   if (NeedsBitcast) {
19321     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
19322     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
19323   }
19324   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
19325   if (VT != And.getValueType())
19326     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19327
19328   // The algorithm mentioned above uses:
19329   //    v = (v * 0x01010101...) >> (Len - 8)
19330   //
19331   // Change it to use vector adds + vector shifts which yield faster results on
19332   // Haswell than using vector integer multiplication.
19333   //
19334   // For i32 elements:
19335   //    v = v + (v >> 8)
19336   //    v = v + (v >> 16)
19337   //
19338   // For i64 elements:
19339   //    v = v + (v >> 8)
19340   //    v = v + (v >> 16)
19341   //    v = v + (v >> 32)
19342   //
19343   Add = And;
19344   SmallVector<SDValue, 8> Csts;
19345   for (unsigned i = 8; i <= Len/2; i *= 2) {
19346     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
19347     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
19348     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
19349     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
19350     Csts.clear();
19351   }
19352
19353   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
19354   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
19355   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
19356   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
19357   if (NeedsBitcast) {
19358     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
19359     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
19360   }
19361   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
19362   if (VT != And.getValueType())
19363     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19364
19365   return And;
19366 }
19367
19368 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19369   SDNode *Node = Op.getNode();
19370   SDLoc dl(Node);
19371   EVT T = Node->getValueType(0);
19372   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19373                               DAG.getConstant(0, T), Node->getOperand(2));
19374   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19375                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19376                        Node->getOperand(0),
19377                        Node->getOperand(1), negOp,
19378                        cast<AtomicSDNode>(Node)->getMemOperand(),
19379                        cast<AtomicSDNode>(Node)->getOrdering(),
19380                        cast<AtomicSDNode>(Node)->getSynchScope());
19381 }
19382
19383 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19384   SDNode *Node = Op.getNode();
19385   SDLoc dl(Node);
19386   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19387
19388   // Convert seq_cst store -> xchg
19389   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19390   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19391   //        (The only way to get a 16-byte store is cmpxchg16b)
19392   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19393   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19394       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19395     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19396                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19397                                  Node->getOperand(0),
19398                                  Node->getOperand(1), Node->getOperand(2),
19399                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19400                                  cast<AtomicSDNode>(Node)->getOrdering(),
19401                                  cast<AtomicSDNode>(Node)->getSynchScope());
19402     return Swap.getValue(1);
19403   }
19404   // Other atomic stores have a simple pattern.
19405   return Op;
19406 }
19407
19408 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19409   EVT VT = Op.getNode()->getSimpleValueType(0);
19410
19411   // Let legalize expand this if it isn't a legal type yet.
19412   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19413     return SDValue();
19414
19415   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19416
19417   unsigned Opc;
19418   bool ExtraOp = false;
19419   switch (Op.getOpcode()) {
19420   default: llvm_unreachable("Invalid code");
19421   case ISD::ADDC: Opc = X86ISD::ADD; break;
19422   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19423   case ISD::SUBC: Opc = X86ISD::SUB; break;
19424   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19425   }
19426
19427   if (!ExtraOp)
19428     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19429                        Op.getOperand(1));
19430   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19431                      Op.getOperand(1), Op.getOperand(2));
19432 }
19433
19434 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19435                             SelectionDAG &DAG) {
19436   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19437
19438   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19439   // which returns the values as { float, float } (in XMM0) or
19440   // { double, double } (which is returned in XMM0, XMM1).
19441   SDLoc dl(Op);
19442   SDValue Arg = Op.getOperand(0);
19443   EVT ArgVT = Arg.getValueType();
19444   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19445
19446   TargetLowering::ArgListTy Args;
19447   TargetLowering::ArgListEntry Entry;
19448
19449   Entry.Node = Arg;
19450   Entry.Ty = ArgTy;
19451   Entry.isSExt = false;
19452   Entry.isZExt = false;
19453   Args.push_back(Entry);
19454
19455   bool isF64 = ArgVT == MVT::f64;
19456   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19457   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19458   // the results are returned via SRet in memory.
19459   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19460   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19461   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
19462
19463   Type *RetTy = isF64
19464     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19465     : (Type*)VectorType::get(ArgTy, 4);
19466
19467   TargetLowering::CallLoweringInfo CLI(DAG);
19468   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19469     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19470
19471   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19472
19473   if (isF64)
19474     // Returned in xmm0 and xmm1.
19475     return CallResult.first;
19476
19477   // Returned in bits 0:31 and 32:64 xmm0.
19478   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19479                                CallResult.first, DAG.getIntPtrConstant(0));
19480   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19481                                CallResult.first, DAG.getIntPtrConstant(1));
19482   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19483   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19484 }
19485
19486 /// LowerOperation - Provide custom lowering hooks for some operations.
19487 ///
19488 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19489   switch (Op.getOpcode()) {
19490   default: llvm_unreachable("Should not custom lower this!");
19491   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
19492   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19493   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19494     return LowerCMP_SWAP(Op, Subtarget, DAG);
19495   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19496   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19497   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19498   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19499   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
19500   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
19501   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19502   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19503   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19504   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19505   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19506   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19507   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19508   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19509   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19510   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19511   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19512   case ISD::SHL_PARTS:
19513   case ISD::SRA_PARTS:
19514   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19515   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19516   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19517   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19518   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19519   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19520   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19521   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19522   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19523   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19524   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19525   case ISD::FABS:
19526   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19527   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19528   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19529   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19530   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19531   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19532   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19533   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19534   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19535   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19536   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19537   case ISD::INTRINSIC_VOID:
19538   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19539   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19540   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19541   case ISD::FRAME_TO_ARGS_OFFSET:
19542                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19543   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19544   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19545   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19546   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19547   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19548   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19549   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19550   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19551   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19552   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
19553   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19554   case ISD::UMUL_LOHI:
19555   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19556   case ISD::SRA:
19557   case ISD::SRL:
19558   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19559   case ISD::SADDO:
19560   case ISD::UADDO:
19561   case ISD::SSUBO:
19562   case ISD::USUBO:
19563   case ISD::SMULO:
19564   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19565   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19566   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19567   case ISD::ADDC:
19568   case ISD::ADDE:
19569   case ISD::SUBC:
19570   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19571   case ISD::ADD:                return LowerADD(Op, DAG);
19572   case ISD::SUB:                return LowerSUB(Op, DAG);
19573   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19574   }
19575 }
19576
19577 /// ReplaceNodeResults - Replace a node with an illegal result type
19578 /// with a new node built out of custom code.
19579 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19580                                            SmallVectorImpl<SDValue>&Results,
19581                                            SelectionDAG &DAG) const {
19582   SDLoc dl(N);
19583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19584   switch (N->getOpcode()) {
19585   default:
19586     llvm_unreachable("Do not know how to custom type legalize this operation!");
19587   case ISD::SIGN_EXTEND_INREG:
19588   case ISD::ADDC:
19589   case ISD::ADDE:
19590   case ISD::SUBC:
19591   case ISD::SUBE:
19592     // We don't want to expand or promote these.
19593     return;
19594   case ISD::SDIV:
19595   case ISD::UDIV:
19596   case ISD::SREM:
19597   case ISD::UREM:
19598   case ISD::SDIVREM:
19599   case ISD::UDIVREM: {
19600     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19601     Results.push_back(V);
19602     return;
19603   }
19604   case ISD::FP_TO_SINT:
19605   case ISD::FP_TO_UINT: {
19606     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19607
19608     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
19609       return;
19610
19611     std::pair<SDValue,SDValue> Vals =
19612         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19613     SDValue FIST = Vals.first, StackSlot = Vals.second;
19614     if (FIST.getNode()) {
19615       EVT VT = N->getValueType(0);
19616       // Return a load from the stack slot.
19617       if (StackSlot.getNode())
19618         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19619                                       MachinePointerInfo(),
19620                                       false, false, false, 0));
19621       else
19622         Results.push_back(FIST);
19623     }
19624     return;
19625   }
19626   case ISD::UINT_TO_FP: {
19627     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19628     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19629         N->getValueType(0) != MVT::v2f32)
19630       return;
19631     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19632                                  N->getOperand(0));
19633     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
19634                                      MVT::f64);
19635     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19636     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19637                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
19638     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
19639     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19640     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19641     return;
19642   }
19643   case ISD::FP_ROUND: {
19644     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19645         return;
19646     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19647     Results.push_back(V);
19648     return;
19649   }
19650   case ISD::INTRINSIC_W_CHAIN: {
19651     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19652     switch (IntNo) {
19653     default : llvm_unreachable("Do not know how to custom type "
19654                                "legalize this intrinsic operation!");
19655     case Intrinsic::x86_rdtsc:
19656       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19657                                      Results);
19658     case Intrinsic::x86_rdtscp:
19659       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19660                                      Results);
19661     case Intrinsic::x86_rdpmc:
19662       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19663     }
19664   }
19665   case ISD::READCYCLECOUNTER: {
19666     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19667                                    Results);
19668   }
19669   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19670     EVT T = N->getValueType(0);
19671     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19672     bool Regs64bit = T == MVT::i128;
19673     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19674     SDValue cpInL, cpInH;
19675     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19676                         DAG.getConstant(0, HalfT));
19677     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19678                         DAG.getConstant(1, HalfT));
19679     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19680                              Regs64bit ? X86::RAX : X86::EAX,
19681                              cpInL, SDValue());
19682     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19683                              Regs64bit ? X86::RDX : X86::EDX,
19684                              cpInH, cpInL.getValue(1));
19685     SDValue swapInL, swapInH;
19686     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19687                           DAG.getConstant(0, HalfT));
19688     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19689                           DAG.getConstant(1, HalfT));
19690     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19691                                Regs64bit ? X86::RBX : X86::EBX,
19692                                swapInL, cpInH.getValue(1));
19693     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19694                                Regs64bit ? X86::RCX : X86::ECX,
19695                                swapInH, swapInL.getValue(1));
19696     SDValue Ops[] = { swapInH.getValue(0),
19697                       N->getOperand(1),
19698                       swapInH.getValue(1) };
19699     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19700     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19701     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19702                                   X86ISD::LCMPXCHG8_DAG;
19703     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19704     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19705                                         Regs64bit ? X86::RAX : X86::EAX,
19706                                         HalfT, Result.getValue(1));
19707     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19708                                         Regs64bit ? X86::RDX : X86::EDX,
19709                                         HalfT, cpOutL.getValue(2));
19710     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19711
19712     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19713                                         MVT::i32, cpOutH.getValue(2));
19714     SDValue Success =
19715         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19716                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19717     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19718
19719     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19720     Results.push_back(Success);
19721     Results.push_back(EFLAGS.getValue(1));
19722     return;
19723   }
19724   case ISD::ATOMIC_SWAP:
19725   case ISD::ATOMIC_LOAD_ADD:
19726   case ISD::ATOMIC_LOAD_SUB:
19727   case ISD::ATOMIC_LOAD_AND:
19728   case ISD::ATOMIC_LOAD_OR:
19729   case ISD::ATOMIC_LOAD_XOR:
19730   case ISD::ATOMIC_LOAD_NAND:
19731   case ISD::ATOMIC_LOAD_MIN:
19732   case ISD::ATOMIC_LOAD_MAX:
19733   case ISD::ATOMIC_LOAD_UMIN:
19734   case ISD::ATOMIC_LOAD_UMAX:
19735   case ISD::ATOMIC_LOAD: {
19736     // Delegate to generic TypeLegalization. Situations we can really handle
19737     // should have already been dealt with by AtomicExpandPass.cpp.
19738     break;
19739   }
19740   case ISD::BITCAST: {
19741     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19742     EVT DstVT = N->getValueType(0);
19743     EVT SrcVT = N->getOperand(0)->getValueType(0);
19744
19745     if (SrcVT != MVT::f64 ||
19746         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19747       return;
19748
19749     unsigned NumElts = DstVT.getVectorNumElements();
19750     EVT SVT = DstVT.getVectorElementType();
19751     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19752     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19753                                    MVT::v2f64, N->getOperand(0));
19754     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
19755
19756     if (ExperimentalVectorWideningLegalization) {
19757       // If we are legalizing vectors by widening, we already have the desired
19758       // legal vector type, just return it.
19759       Results.push_back(ToVecInt);
19760       return;
19761     }
19762
19763     SmallVector<SDValue, 8> Elts;
19764     for (unsigned i = 0, e = NumElts; i != e; ++i)
19765       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19766                                    ToVecInt, DAG.getIntPtrConstant(i)));
19767
19768     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19769   }
19770   }
19771 }
19772
19773 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19774   switch (Opcode) {
19775   default: return nullptr;
19776   case X86ISD::BSF:                return "X86ISD::BSF";
19777   case X86ISD::BSR:                return "X86ISD::BSR";
19778   case X86ISD::SHLD:               return "X86ISD::SHLD";
19779   case X86ISD::SHRD:               return "X86ISD::SHRD";
19780   case X86ISD::FAND:               return "X86ISD::FAND";
19781   case X86ISD::FANDN:              return "X86ISD::FANDN";
19782   case X86ISD::FOR:                return "X86ISD::FOR";
19783   case X86ISD::FXOR:               return "X86ISD::FXOR";
19784   case X86ISD::FSRL:               return "X86ISD::FSRL";
19785   case X86ISD::FILD:               return "X86ISD::FILD";
19786   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19787   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19788   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19789   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19790   case X86ISD::FLD:                return "X86ISD::FLD";
19791   case X86ISD::FST:                return "X86ISD::FST";
19792   case X86ISD::CALL:               return "X86ISD::CALL";
19793   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19794   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19795   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19796   case X86ISD::BT:                 return "X86ISD::BT";
19797   case X86ISD::CMP:                return "X86ISD::CMP";
19798   case X86ISD::COMI:               return "X86ISD::COMI";
19799   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19800   case X86ISD::CMPM:               return "X86ISD::CMPM";
19801   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19802   case X86ISD::SETCC:              return "X86ISD::SETCC";
19803   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19804   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19805   case X86ISD::CMOV:               return "X86ISD::CMOV";
19806   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19807   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19808   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19809   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19810   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19811   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19812   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19813   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19814   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19815   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19816   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19817   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19818   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19819   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19820   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19821   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19822   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19823   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19824   case X86ISD::HADD:               return "X86ISD::HADD";
19825   case X86ISD::HSUB:               return "X86ISD::HSUB";
19826   case X86ISD::FHADD:              return "X86ISD::FHADD";
19827   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19828   case X86ISD::UMAX:               return "X86ISD::UMAX";
19829   case X86ISD::UMIN:               return "X86ISD::UMIN";
19830   case X86ISD::SMAX:               return "X86ISD::SMAX";
19831   case X86ISD::SMIN:               return "X86ISD::SMIN";
19832   case X86ISD::FMAX:               return "X86ISD::FMAX";
19833   case X86ISD::FMIN:               return "X86ISD::FMIN";
19834   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19835   case X86ISD::FMINC:              return "X86ISD::FMINC";
19836   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19837   case X86ISD::FRCP:               return "X86ISD::FRCP";
19838   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19839   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19840   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19841   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19842   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19843   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19844   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19845   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19846   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19847   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19848   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19849   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19850   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19851   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19852   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19853   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19854   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19855   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
19856   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19857   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19858   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19859   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19860   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19861   case X86ISD::VSHL:               return "X86ISD::VSHL";
19862   case X86ISD::VSRL:               return "X86ISD::VSRL";
19863   case X86ISD::VSRA:               return "X86ISD::VSRA";
19864   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19865   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19866   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19867   case X86ISD::CMPP:               return "X86ISD::CMPP";
19868   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19869   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19870   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19871   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19872   case X86ISD::ADD:                return "X86ISD::ADD";
19873   case X86ISD::SUB:                return "X86ISD::SUB";
19874   case X86ISD::ADC:                return "X86ISD::ADC";
19875   case X86ISD::SBB:                return "X86ISD::SBB";
19876   case X86ISD::SMUL:               return "X86ISD::SMUL";
19877   case X86ISD::UMUL:               return "X86ISD::UMUL";
19878   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19879   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19880   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19881   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19882   case X86ISD::INC:                return "X86ISD::INC";
19883   case X86ISD::DEC:                return "X86ISD::DEC";
19884   case X86ISD::OR:                 return "X86ISD::OR";
19885   case X86ISD::XOR:                return "X86ISD::XOR";
19886   case X86ISD::AND:                return "X86ISD::AND";
19887   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19888   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19889   case X86ISD::PTEST:              return "X86ISD::PTEST";
19890   case X86ISD::TESTP:              return "X86ISD::TESTP";
19891   case X86ISD::TESTM:              return "X86ISD::TESTM";
19892   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19893   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19894   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19895   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19896   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19897   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19898   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19899   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19900   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19901   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19902   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19903   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19904   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19905   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19906   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19907   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19908   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19909   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19910   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19911   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19912   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19913   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19914   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19915   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
19916   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19917   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19918   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19919   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19920   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19921   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19922   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19923   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19924   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19925   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19926   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19927   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19928   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19929   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19930   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19931   case X86ISD::SAHF:               return "X86ISD::SAHF";
19932   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19933   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19934   case X86ISD::FMADD:              return "X86ISD::FMADD";
19935   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19936   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19937   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19938   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19939   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19940   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19941   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19942   case X86ISD::XTEST:              return "X86ISD::XTEST";
19943   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19944   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19945   case X86ISD::SELECT:             return "X86ISD::SELECT";
19946   }
19947 }
19948
19949 // isLegalAddressingMode - Return true if the addressing mode represented
19950 // by AM is legal for this target, for a load/store of the specified type.
19951 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
19952                                               Type *Ty) const {
19953   // X86 supports extremely general addressing modes.
19954   CodeModel::Model M = getTargetMachine().getCodeModel();
19955   Reloc::Model R = getTargetMachine().getRelocationModel();
19956
19957   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19958   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19959     return false;
19960
19961   if (AM.BaseGV) {
19962     unsigned GVFlags =
19963       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19964
19965     // If a reference to this global requires an extra load, we can't fold it.
19966     if (isGlobalStubReference(GVFlags))
19967       return false;
19968
19969     // If BaseGV requires a register for the PIC base, we cannot also have a
19970     // BaseReg specified.
19971     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19972       return false;
19973
19974     // If lower 4G is not available, then we must use rip-relative addressing.
19975     if ((M != CodeModel::Small || R != Reloc::Static) &&
19976         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19977       return false;
19978   }
19979
19980   switch (AM.Scale) {
19981   case 0:
19982   case 1:
19983   case 2:
19984   case 4:
19985   case 8:
19986     // These scales always work.
19987     break;
19988   case 3:
19989   case 5:
19990   case 9:
19991     // These scales are formed with basereg+scalereg.  Only accept if there is
19992     // no basereg yet.
19993     if (AM.HasBaseReg)
19994       return false;
19995     break;
19996   default:  // Other stuff never works.
19997     return false;
19998   }
19999
20000   return true;
20001 }
20002
20003 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20004   unsigned Bits = Ty->getScalarSizeInBits();
20005
20006   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20007   // particularly cheaper than those without.
20008   if (Bits == 8)
20009     return false;
20010
20011   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20012   // variable shifts just as cheap as scalar ones.
20013   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20014     return false;
20015
20016   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20017   // fully general vector.
20018   return true;
20019 }
20020
20021 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20022   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20023     return false;
20024   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20025   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20026   return NumBits1 > NumBits2;
20027 }
20028
20029 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20030   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20031     return false;
20032
20033   if (!isTypeLegal(EVT::getEVT(Ty1)))
20034     return false;
20035
20036   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20037
20038   // Assuming the caller doesn't have a zeroext or signext return parameter,
20039   // truncation all the way down to i1 is valid.
20040   return true;
20041 }
20042
20043 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20044   return isInt<32>(Imm);
20045 }
20046
20047 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20048   // Can also use sub to handle negated immediates.
20049   return isInt<32>(Imm);
20050 }
20051
20052 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20053   if (!VT1.isInteger() || !VT2.isInteger())
20054     return false;
20055   unsigned NumBits1 = VT1.getSizeInBits();
20056   unsigned NumBits2 = VT2.getSizeInBits();
20057   return NumBits1 > NumBits2;
20058 }
20059
20060 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20061   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20062   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20063 }
20064
20065 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20066   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20067   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20068 }
20069
20070 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20071   EVT VT1 = Val.getValueType();
20072   if (isZExtFree(VT1, VT2))
20073     return true;
20074
20075   if (Val.getOpcode() != ISD::LOAD)
20076     return false;
20077
20078   if (!VT1.isSimple() || !VT1.isInteger() ||
20079       !VT2.isSimple() || !VT2.isInteger())
20080     return false;
20081
20082   switch (VT1.getSimpleVT().SimpleTy) {
20083   default: break;
20084   case MVT::i8:
20085   case MVT::i16:
20086   case MVT::i32:
20087     // X86 has 8, 16, and 32-bit zero-extending loads.
20088     return true;
20089   }
20090
20091   return false;
20092 }
20093
20094 bool
20095 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20096   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
20097     return false;
20098
20099   VT = VT.getScalarType();
20100
20101   if (!VT.isSimple())
20102     return false;
20103
20104   switch (VT.getSimpleVT().SimpleTy) {
20105   case MVT::f32:
20106   case MVT::f64:
20107     return true;
20108   default:
20109     break;
20110   }
20111
20112   return false;
20113 }
20114
20115 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20116   // i16 instructions are longer (0x66 prefix) and potentially slower.
20117   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20118 }
20119
20120 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20121 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20122 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20123 /// are assumed to be legal.
20124 bool
20125 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20126                                       EVT VT) const {
20127   if (!VT.isSimple())
20128     return false;
20129
20130   MVT SVT = VT.getSimpleVT();
20131
20132   // Very little shuffling can be done for 64-bit vectors right now.
20133   if (VT.getSizeInBits() == 64)
20134     return false;
20135
20136   // If this is a single-input shuffle with no 128 bit lane crossings we can
20137   // lower it into pshufb.
20138   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
20139       (SVT.is256BitVector() && Subtarget->hasInt256())) {
20140     bool isLegal = true;
20141     for (unsigned I = 0, E = M.size(); I != E; ++I) {
20142       if (M[I] >= (int)SVT.getVectorNumElements() ||
20143           ShuffleCrosses128bitLane(SVT, I, M[I])) {
20144         isLegal = false;
20145         break;
20146       }
20147     }
20148     if (isLegal)
20149       return true;
20150   }
20151
20152   // FIXME: blends, shifts.
20153   return (SVT.getVectorNumElements() == 2 ||
20154           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
20155           isMOVLMask(M, SVT) ||
20156           isCommutedMOVLMask(M, SVT) ||
20157           isMOVHLPSMask(M, SVT) ||
20158           isSHUFPMask(M, SVT) ||
20159           isSHUFPMask(M, SVT, /* Commuted */ true) ||
20160           isPSHUFDMask(M, SVT) ||
20161           isPSHUFDMask(M, SVT, /* SecondOperand */ true) ||
20162           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
20163           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
20164           isPALIGNRMask(M, SVT, Subtarget) ||
20165           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
20166           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
20167           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
20168           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
20169           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()) ||
20170           (Subtarget->hasSSE41() && isINSERTPSMask(M, SVT)));
20171 }
20172
20173 bool
20174 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20175                                           EVT VT) const {
20176   if (!VT.isSimple())
20177     return false;
20178
20179   MVT SVT = VT.getSimpleVT();
20180   unsigned NumElts = SVT.getVectorNumElements();
20181   // FIXME: This collection of masks seems suspect.
20182   if (NumElts == 2)
20183     return true;
20184   if (NumElts == 4 && SVT.is128BitVector()) {
20185     return (isMOVLMask(Mask, SVT)  ||
20186             isCommutedMOVLMask(Mask, SVT, true) ||
20187             isSHUFPMask(Mask, SVT) ||
20188             isSHUFPMask(Mask, SVT, /* Commuted */ true) ||
20189             isBlendMask(Mask, SVT, Subtarget->hasSSE41(),
20190                         Subtarget->hasInt256()));
20191   }
20192   return false;
20193 }
20194
20195 //===----------------------------------------------------------------------===//
20196 //                           X86 Scheduler Hooks
20197 //===----------------------------------------------------------------------===//
20198
20199 /// Utility function to emit xbegin specifying the start of an RTM region.
20200 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20201                                      const TargetInstrInfo *TII) {
20202   DebugLoc DL = MI->getDebugLoc();
20203
20204   const BasicBlock *BB = MBB->getBasicBlock();
20205   MachineFunction::iterator I = MBB;
20206   ++I;
20207
20208   // For the v = xbegin(), we generate
20209   //
20210   // thisMBB:
20211   //  xbegin sinkMBB
20212   //
20213   // mainMBB:
20214   //  eax = -1
20215   //
20216   // sinkMBB:
20217   //  v = eax
20218
20219   MachineBasicBlock *thisMBB = MBB;
20220   MachineFunction *MF = MBB->getParent();
20221   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20222   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20223   MF->insert(I, mainMBB);
20224   MF->insert(I, sinkMBB);
20225
20226   // Transfer the remainder of BB and its successor edges to sinkMBB.
20227   sinkMBB->splice(sinkMBB->begin(), MBB,
20228                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20229   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20230
20231   // thisMBB:
20232   //  xbegin sinkMBB
20233   //  # fallthrough to mainMBB
20234   //  # abortion to sinkMBB
20235   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20236   thisMBB->addSuccessor(mainMBB);
20237   thisMBB->addSuccessor(sinkMBB);
20238
20239   // mainMBB:
20240   //  EAX = -1
20241   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20242   mainMBB->addSuccessor(sinkMBB);
20243
20244   // sinkMBB:
20245   // EAX is live into the sinkMBB
20246   sinkMBB->addLiveIn(X86::EAX);
20247   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20248           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20249     .addReg(X86::EAX);
20250
20251   MI->eraseFromParent();
20252   return sinkMBB;
20253 }
20254
20255 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20256 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20257 // in the .td file.
20258 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20259                                        const TargetInstrInfo *TII) {
20260   unsigned Opc;
20261   switch (MI->getOpcode()) {
20262   default: llvm_unreachable("illegal opcode!");
20263   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20264   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20265   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20266   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20267   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20268   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20269   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20270   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20271   }
20272
20273   DebugLoc dl = MI->getDebugLoc();
20274   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20275
20276   unsigned NumArgs = MI->getNumOperands();
20277   for (unsigned i = 1; i < NumArgs; ++i) {
20278     MachineOperand &Op = MI->getOperand(i);
20279     if (!(Op.isReg() && Op.isImplicit()))
20280       MIB.addOperand(Op);
20281   }
20282   if (MI->hasOneMemOperand())
20283     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20284
20285   BuildMI(*BB, MI, dl,
20286     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20287     .addReg(X86::XMM0);
20288
20289   MI->eraseFromParent();
20290   return BB;
20291 }
20292
20293 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20294 // defs in an instruction pattern
20295 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20296                                        const TargetInstrInfo *TII) {
20297   unsigned Opc;
20298   switch (MI->getOpcode()) {
20299   default: llvm_unreachable("illegal opcode!");
20300   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20301   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20302   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20303   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20304   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20305   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20306   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20307   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20308   }
20309
20310   DebugLoc dl = MI->getDebugLoc();
20311   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20312
20313   unsigned NumArgs = MI->getNumOperands(); // remove the results
20314   for (unsigned i = 1; i < NumArgs; ++i) {
20315     MachineOperand &Op = MI->getOperand(i);
20316     if (!(Op.isReg() && Op.isImplicit()))
20317       MIB.addOperand(Op);
20318   }
20319   if (MI->hasOneMemOperand())
20320     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20321
20322   BuildMI(*BB, MI, dl,
20323     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20324     .addReg(X86::ECX);
20325
20326   MI->eraseFromParent();
20327   return BB;
20328 }
20329
20330 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20331                                        const TargetInstrInfo *TII,
20332                                        const X86Subtarget* Subtarget) {
20333   DebugLoc dl = MI->getDebugLoc();
20334
20335   // Address into RAX/EAX, other two args into ECX, EDX.
20336   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20337   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20338   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20339   for (int i = 0; i < X86::AddrNumOperands; ++i)
20340     MIB.addOperand(MI->getOperand(i));
20341
20342   unsigned ValOps = X86::AddrNumOperands;
20343   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20344     .addReg(MI->getOperand(ValOps).getReg());
20345   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20346     .addReg(MI->getOperand(ValOps+1).getReg());
20347
20348   // The instruction doesn't actually take any operands though.
20349   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20350
20351   MI->eraseFromParent(); // The pseudo is gone now.
20352   return BB;
20353 }
20354
20355 MachineBasicBlock *
20356 X86TargetLowering::EmitVAARG64WithCustomInserter(
20357                    MachineInstr *MI,
20358                    MachineBasicBlock *MBB) const {
20359   // Emit va_arg instruction on X86-64.
20360
20361   // Operands to this pseudo-instruction:
20362   // 0  ) Output        : destination address (reg)
20363   // 1-5) Input         : va_list address (addr, i64mem)
20364   // 6  ) ArgSize       : Size (in bytes) of vararg type
20365   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20366   // 8  ) Align         : Alignment of type
20367   // 9  ) EFLAGS (implicit-def)
20368
20369   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20370   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
20371
20372   unsigned DestReg = MI->getOperand(0).getReg();
20373   MachineOperand &Base = MI->getOperand(1);
20374   MachineOperand &Scale = MI->getOperand(2);
20375   MachineOperand &Index = MI->getOperand(3);
20376   MachineOperand &Disp = MI->getOperand(4);
20377   MachineOperand &Segment = MI->getOperand(5);
20378   unsigned ArgSize = MI->getOperand(6).getImm();
20379   unsigned ArgMode = MI->getOperand(7).getImm();
20380   unsigned Align = MI->getOperand(8).getImm();
20381
20382   // Memory Reference
20383   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20384   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20385   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20386
20387   // Machine Information
20388   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20389   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20390   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20391   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20392   DebugLoc DL = MI->getDebugLoc();
20393
20394   // struct va_list {
20395   //   i32   gp_offset
20396   //   i32   fp_offset
20397   //   i64   overflow_area (address)
20398   //   i64   reg_save_area (address)
20399   // }
20400   // sizeof(va_list) = 24
20401   // alignment(va_list) = 8
20402
20403   unsigned TotalNumIntRegs = 6;
20404   unsigned TotalNumXMMRegs = 8;
20405   bool UseGPOffset = (ArgMode == 1);
20406   bool UseFPOffset = (ArgMode == 2);
20407   unsigned MaxOffset = TotalNumIntRegs * 8 +
20408                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20409
20410   /* Align ArgSize to a multiple of 8 */
20411   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20412   bool NeedsAlign = (Align > 8);
20413
20414   MachineBasicBlock *thisMBB = MBB;
20415   MachineBasicBlock *overflowMBB;
20416   MachineBasicBlock *offsetMBB;
20417   MachineBasicBlock *endMBB;
20418
20419   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20420   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20421   unsigned OffsetReg = 0;
20422
20423   if (!UseGPOffset && !UseFPOffset) {
20424     // If we only pull from the overflow region, we don't create a branch.
20425     // We don't need to alter control flow.
20426     OffsetDestReg = 0; // unused
20427     OverflowDestReg = DestReg;
20428
20429     offsetMBB = nullptr;
20430     overflowMBB = thisMBB;
20431     endMBB = thisMBB;
20432   } else {
20433     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20434     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20435     // If not, pull from overflow_area. (branch to overflowMBB)
20436     //
20437     //       thisMBB
20438     //         |     .
20439     //         |        .
20440     //     offsetMBB   overflowMBB
20441     //         |        .
20442     //         |     .
20443     //        endMBB
20444
20445     // Registers for the PHI in endMBB
20446     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20447     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20448
20449     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20450     MachineFunction *MF = MBB->getParent();
20451     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20452     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20453     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20454
20455     MachineFunction::iterator MBBIter = MBB;
20456     ++MBBIter;
20457
20458     // Insert the new basic blocks
20459     MF->insert(MBBIter, offsetMBB);
20460     MF->insert(MBBIter, overflowMBB);
20461     MF->insert(MBBIter, endMBB);
20462
20463     // Transfer the remainder of MBB and its successor edges to endMBB.
20464     endMBB->splice(endMBB->begin(), thisMBB,
20465                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20466     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20467
20468     // Make offsetMBB and overflowMBB successors of thisMBB
20469     thisMBB->addSuccessor(offsetMBB);
20470     thisMBB->addSuccessor(overflowMBB);
20471
20472     // endMBB is a successor of both offsetMBB and overflowMBB
20473     offsetMBB->addSuccessor(endMBB);
20474     overflowMBB->addSuccessor(endMBB);
20475
20476     // Load the offset value into a register
20477     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20478     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20479       .addOperand(Base)
20480       .addOperand(Scale)
20481       .addOperand(Index)
20482       .addDisp(Disp, UseFPOffset ? 4 : 0)
20483       .addOperand(Segment)
20484       .setMemRefs(MMOBegin, MMOEnd);
20485
20486     // Check if there is enough room left to pull this argument.
20487     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20488       .addReg(OffsetReg)
20489       .addImm(MaxOffset + 8 - ArgSizeA8);
20490
20491     // Branch to "overflowMBB" if offset >= max
20492     // Fall through to "offsetMBB" otherwise
20493     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20494       .addMBB(overflowMBB);
20495   }
20496
20497   // In offsetMBB, emit code to use the reg_save_area.
20498   if (offsetMBB) {
20499     assert(OffsetReg != 0);
20500
20501     // Read the reg_save_area address.
20502     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20503     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20504       .addOperand(Base)
20505       .addOperand(Scale)
20506       .addOperand(Index)
20507       .addDisp(Disp, 16)
20508       .addOperand(Segment)
20509       .setMemRefs(MMOBegin, MMOEnd);
20510
20511     // Zero-extend the offset
20512     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20513       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20514         .addImm(0)
20515         .addReg(OffsetReg)
20516         .addImm(X86::sub_32bit);
20517
20518     // Add the offset to the reg_save_area to get the final address.
20519     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20520       .addReg(OffsetReg64)
20521       .addReg(RegSaveReg);
20522
20523     // Compute the offset for the next argument
20524     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20525     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20526       .addReg(OffsetReg)
20527       .addImm(UseFPOffset ? 16 : 8);
20528
20529     // Store it back into the va_list.
20530     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20531       .addOperand(Base)
20532       .addOperand(Scale)
20533       .addOperand(Index)
20534       .addDisp(Disp, UseFPOffset ? 4 : 0)
20535       .addOperand(Segment)
20536       .addReg(NextOffsetReg)
20537       .setMemRefs(MMOBegin, MMOEnd);
20538
20539     // Jump to endMBB
20540     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20541       .addMBB(endMBB);
20542   }
20543
20544   //
20545   // Emit code to use overflow area
20546   //
20547
20548   // Load the overflow_area address into a register.
20549   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20550   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20551     .addOperand(Base)
20552     .addOperand(Scale)
20553     .addOperand(Index)
20554     .addDisp(Disp, 8)
20555     .addOperand(Segment)
20556     .setMemRefs(MMOBegin, MMOEnd);
20557
20558   // If we need to align it, do so. Otherwise, just copy the address
20559   // to OverflowDestReg.
20560   if (NeedsAlign) {
20561     // Align the overflow address
20562     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20563     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20564
20565     // aligned_addr = (addr + (align-1)) & ~(align-1)
20566     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20567       .addReg(OverflowAddrReg)
20568       .addImm(Align-1);
20569
20570     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20571       .addReg(TmpReg)
20572       .addImm(~(uint64_t)(Align-1));
20573   } else {
20574     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20575       .addReg(OverflowAddrReg);
20576   }
20577
20578   // Compute the next overflow address after this argument.
20579   // (the overflow address should be kept 8-byte aligned)
20580   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20581   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20582     .addReg(OverflowDestReg)
20583     .addImm(ArgSizeA8);
20584
20585   // Store the new overflow address.
20586   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20587     .addOperand(Base)
20588     .addOperand(Scale)
20589     .addOperand(Index)
20590     .addDisp(Disp, 8)
20591     .addOperand(Segment)
20592     .addReg(NextAddrReg)
20593     .setMemRefs(MMOBegin, MMOEnd);
20594
20595   // If we branched, emit the PHI to the front of endMBB.
20596   if (offsetMBB) {
20597     BuildMI(*endMBB, endMBB->begin(), DL,
20598             TII->get(X86::PHI), DestReg)
20599       .addReg(OffsetDestReg).addMBB(offsetMBB)
20600       .addReg(OverflowDestReg).addMBB(overflowMBB);
20601   }
20602
20603   // Erase the pseudo instruction
20604   MI->eraseFromParent();
20605
20606   return endMBB;
20607 }
20608
20609 MachineBasicBlock *
20610 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20611                                                  MachineInstr *MI,
20612                                                  MachineBasicBlock *MBB) const {
20613   // Emit code to save XMM registers to the stack. The ABI says that the
20614   // number of registers to save is given in %al, so it's theoretically
20615   // possible to do an indirect jump trick to avoid saving all of them,
20616   // however this code takes a simpler approach and just executes all
20617   // of the stores if %al is non-zero. It's less code, and it's probably
20618   // easier on the hardware branch predictor, and stores aren't all that
20619   // expensive anyway.
20620
20621   // Create the new basic blocks. One block contains all the XMM stores,
20622   // and one block is the final destination regardless of whether any
20623   // stores were performed.
20624   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20625   MachineFunction *F = MBB->getParent();
20626   MachineFunction::iterator MBBIter = MBB;
20627   ++MBBIter;
20628   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20629   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20630   F->insert(MBBIter, XMMSaveMBB);
20631   F->insert(MBBIter, EndMBB);
20632
20633   // Transfer the remainder of MBB and its successor edges to EndMBB.
20634   EndMBB->splice(EndMBB->begin(), MBB,
20635                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20636   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20637
20638   // The original block will now fall through to the XMM save block.
20639   MBB->addSuccessor(XMMSaveMBB);
20640   // The XMMSaveMBB will fall through to the end block.
20641   XMMSaveMBB->addSuccessor(EndMBB);
20642
20643   // Now add the instructions.
20644   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20645   DebugLoc DL = MI->getDebugLoc();
20646
20647   unsigned CountReg = MI->getOperand(0).getReg();
20648   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20649   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20650
20651   if (!Subtarget->isTargetWin64()) {
20652     // If %al is 0, branch around the XMM save block.
20653     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20654     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20655     MBB->addSuccessor(EndMBB);
20656   }
20657
20658   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20659   // that was just emitted, but clearly shouldn't be "saved".
20660   assert((MI->getNumOperands() <= 3 ||
20661           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20662           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20663          && "Expected last argument to be EFLAGS");
20664   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20665   // In the XMM save block, save all the XMM argument registers.
20666   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20667     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20668     MachineMemOperand *MMO =
20669       F->getMachineMemOperand(
20670           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
20671         MachineMemOperand::MOStore,
20672         /*Size=*/16, /*Align=*/16);
20673     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20674       .addFrameIndex(RegSaveFrameIndex)
20675       .addImm(/*Scale=*/1)
20676       .addReg(/*IndexReg=*/0)
20677       .addImm(/*Disp=*/Offset)
20678       .addReg(/*Segment=*/0)
20679       .addReg(MI->getOperand(i).getReg())
20680       .addMemOperand(MMO);
20681   }
20682
20683   MI->eraseFromParent();   // The pseudo instruction is gone now.
20684
20685   return EndMBB;
20686 }
20687
20688 // The EFLAGS operand of SelectItr might be missing a kill marker
20689 // because there were multiple uses of EFLAGS, and ISel didn't know
20690 // which to mark. Figure out whether SelectItr should have had a
20691 // kill marker, and set it if it should. Returns the correct kill
20692 // marker value.
20693 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20694                                      MachineBasicBlock* BB,
20695                                      const TargetRegisterInfo* TRI) {
20696   // Scan forward through BB for a use/def of EFLAGS.
20697   MachineBasicBlock::iterator miI(std::next(SelectItr));
20698   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20699     const MachineInstr& mi = *miI;
20700     if (mi.readsRegister(X86::EFLAGS))
20701       return false;
20702     if (mi.definesRegister(X86::EFLAGS))
20703       break; // Should have kill-flag - update below.
20704   }
20705
20706   // If we hit the end of the block, check whether EFLAGS is live into a
20707   // successor.
20708   if (miI == BB->end()) {
20709     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20710                                           sEnd = BB->succ_end();
20711          sItr != sEnd; ++sItr) {
20712       MachineBasicBlock* succ = *sItr;
20713       if (succ->isLiveIn(X86::EFLAGS))
20714         return false;
20715     }
20716   }
20717
20718   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20719   // out. SelectMI should have a kill flag on EFLAGS.
20720   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20721   return true;
20722 }
20723
20724 MachineBasicBlock *
20725 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20726                                      MachineBasicBlock *BB) const {
20727   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20728   DebugLoc DL = MI->getDebugLoc();
20729
20730   // To "insert" a SELECT_CC instruction, we actually have to insert the
20731   // diamond control-flow pattern.  The incoming instruction knows the
20732   // destination vreg to set, the condition code register to branch on, the
20733   // true/false values to select between, and a branch opcode to use.
20734   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20735   MachineFunction::iterator It = BB;
20736   ++It;
20737
20738   //  thisMBB:
20739   //  ...
20740   //   TrueVal = ...
20741   //   cmpTY ccX, r1, r2
20742   //   bCC copy1MBB
20743   //   fallthrough --> copy0MBB
20744   MachineBasicBlock *thisMBB = BB;
20745   MachineFunction *F = BB->getParent();
20746   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20747   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20748   F->insert(It, copy0MBB);
20749   F->insert(It, sinkMBB);
20750
20751   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20752   // live into the sink and copy blocks.
20753   const TargetRegisterInfo *TRI =
20754       BB->getParent()->getSubtarget().getRegisterInfo();
20755   if (!MI->killsRegister(X86::EFLAGS) &&
20756       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
20757     copy0MBB->addLiveIn(X86::EFLAGS);
20758     sinkMBB->addLiveIn(X86::EFLAGS);
20759   }
20760
20761   // Transfer the remainder of BB and its successor edges to sinkMBB.
20762   sinkMBB->splice(sinkMBB->begin(), BB,
20763                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20764   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20765
20766   // Add the true and fallthrough blocks as its successors.
20767   BB->addSuccessor(copy0MBB);
20768   BB->addSuccessor(sinkMBB);
20769
20770   // Create the conditional branch instruction.
20771   unsigned Opc =
20772     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20773   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20774
20775   //  copy0MBB:
20776   //   %FalseValue = ...
20777   //   # fallthrough to sinkMBB
20778   copy0MBB->addSuccessor(sinkMBB);
20779
20780   //  sinkMBB:
20781   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20782   //  ...
20783   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20784           TII->get(X86::PHI), MI->getOperand(0).getReg())
20785     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20786     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20787
20788   MI->eraseFromParent();   // The pseudo instruction is gone now.
20789   return sinkMBB;
20790 }
20791
20792 MachineBasicBlock *
20793 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20794                                         MachineBasicBlock *BB) const {
20795   MachineFunction *MF = BB->getParent();
20796   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20797   DebugLoc DL = MI->getDebugLoc();
20798   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20799
20800   assert(MF->shouldSplitStack());
20801
20802   const bool Is64Bit = Subtarget->is64Bit();
20803   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20804
20805   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20806   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20807
20808   // BB:
20809   //  ... [Till the alloca]
20810   // If stacklet is not large enough, jump to mallocMBB
20811   //
20812   // bumpMBB:
20813   //  Allocate by subtracting from RSP
20814   //  Jump to continueMBB
20815   //
20816   // mallocMBB:
20817   //  Allocate by call to runtime
20818   //
20819   // continueMBB:
20820   //  ...
20821   //  [rest of original BB]
20822   //
20823
20824   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20825   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20826   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20827
20828   MachineRegisterInfo &MRI = MF->getRegInfo();
20829   const TargetRegisterClass *AddrRegClass =
20830     getRegClassFor(getPointerTy());
20831
20832   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20833     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20834     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20835     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20836     sizeVReg = MI->getOperand(1).getReg(),
20837     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20838
20839   MachineFunction::iterator MBBIter = BB;
20840   ++MBBIter;
20841
20842   MF->insert(MBBIter, bumpMBB);
20843   MF->insert(MBBIter, mallocMBB);
20844   MF->insert(MBBIter, continueMBB);
20845
20846   continueMBB->splice(continueMBB->begin(), BB,
20847                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20848   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20849
20850   // Add code to the main basic block to check if the stack limit has been hit,
20851   // and if so, jump to mallocMBB otherwise to bumpMBB.
20852   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20853   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20854     .addReg(tmpSPVReg).addReg(sizeVReg);
20855   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20856     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20857     .addReg(SPLimitVReg);
20858   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20859
20860   // bumpMBB simply decreases the stack pointer, since we know the current
20861   // stacklet has enough space.
20862   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20863     .addReg(SPLimitVReg);
20864   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20865     .addReg(SPLimitVReg);
20866   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20867
20868   // Calls into a routine in libgcc to allocate more space from the heap.
20869   const uint32_t *RegMask = MF->getTarget()
20870                                 .getSubtargetImpl()
20871                                 ->getRegisterInfo()
20872                                 ->getCallPreservedMask(CallingConv::C);
20873   if (IsLP64) {
20874     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20875       .addReg(sizeVReg);
20876     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20877       .addExternalSymbol("__morestack_allocate_stack_space")
20878       .addRegMask(RegMask)
20879       .addReg(X86::RDI, RegState::Implicit)
20880       .addReg(X86::RAX, RegState::ImplicitDefine);
20881   } else if (Is64Bit) {
20882     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20883       .addReg(sizeVReg);
20884     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20885       .addExternalSymbol("__morestack_allocate_stack_space")
20886       .addRegMask(RegMask)
20887       .addReg(X86::EDI, RegState::Implicit)
20888       .addReg(X86::EAX, RegState::ImplicitDefine);
20889   } else {
20890     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20891       .addImm(12);
20892     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20893     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20894       .addExternalSymbol("__morestack_allocate_stack_space")
20895       .addRegMask(RegMask)
20896       .addReg(X86::EAX, RegState::ImplicitDefine);
20897   }
20898
20899   if (!Is64Bit)
20900     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20901       .addImm(16);
20902
20903   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20904     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20905   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20906
20907   // Set up the CFG correctly.
20908   BB->addSuccessor(bumpMBB);
20909   BB->addSuccessor(mallocMBB);
20910   mallocMBB->addSuccessor(continueMBB);
20911   bumpMBB->addSuccessor(continueMBB);
20912
20913   // Take care of the PHI nodes.
20914   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20915           MI->getOperand(0).getReg())
20916     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20917     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20918
20919   // Delete the original pseudo instruction.
20920   MI->eraseFromParent();
20921
20922   // And we're done.
20923   return continueMBB;
20924 }
20925
20926 MachineBasicBlock *
20927 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20928                                         MachineBasicBlock *BB) const {
20929   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20930   DebugLoc DL = MI->getDebugLoc();
20931
20932   assert(!Subtarget->isTargetMachO());
20933
20934   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
20935   // non-trivial part is impdef of ESP.
20936
20937   if (Subtarget->isTargetWin64()) {
20938     if (Subtarget->isTargetCygMing()) {
20939       // ___chkstk(Mingw64):
20940       // Clobbers R10, R11, RAX and EFLAGS.
20941       // Updates RSP.
20942       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20943         .addExternalSymbol("___chkstk")
20944         .addReg(X86::RAX, RegState::Implicit)
20945         .addReg(X86::RSP, RegState::Implicit)
20946         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
20947         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
20948         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20949     } else {
20950       // __chkstk(MSVCRT): does not update stack pointer.
20951       // Clobbers R10, R11 and EFLAGS.
20952       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20953         .addExternalSymbol("__chkstk")
20954         .addReg(X86::RAX, RegState::Implicit)
20955         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20956       // RAX has the offset to be subtracted from RSP.
20957       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
20958         .addReg(X86::RSP)
20959         .addReg(X86::RAX);
20960     }
20961   } else {
20962     const char *StackProbeSymbol = (Subtarget->isTargetKnownWindowsMSVC() ||
20963                                     Subtarget->isTargetWindowsItanium())
20964                                        ? "_chkstk"
20965                                        : "_alloca";
20966
20967     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
20968       .addExternalSymbol(StackProbeSymbol)
20969       .addReg(X86::EAX, RegState::Implicit)
20970       .addReg(X86::ESP, RegState::Implicit)
20971       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
20972       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
20973       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20974   }
20975
20976   MI->eraseFromParent();   // The pseudo instruction is gone now.
20977   return BB;
20978 }
20979
20980 MachineBasicBlock *
20981 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20982                                       MachineBasicBlock *BB) const {
20983   // This is pretty easy.  We're taking the value that we received from
20984   // our load from the relocation, sticking it in either RDI (x86-64)
20985   // or EAX and doing an indirect call.  The return value will then
20986   // be in the normal return register.
20987   MachineFunction *F = BB->getParent();
20988   const X86InstrInfo *TII =
20989       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
20990   DebugLoc DL = MI->getDebugLoc();
20991
20992   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20993   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20994
20995   // Get a register mask for the lowered call.
20996   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20997   // proper register mask.
20998   const uint32_t *RegMask = F->getTarget()
20999                                 .getSubtargetImpl()
21000                                 ->getRegisterInfo()
21001                                 ->getCallPreservedMask(CallingConv::C);
21002   if (Subtarget->is64Bit()) {
21003     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21004                                       TII->get(X86::MOV64rm), X86::RDI)
21005     .addReg(X86::RIP)
21006     .addImm(0).addReg(0)
21007     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21008                       MI->getOperand(3).getTargetFlags())
21009     .addReg(0);
21010     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21011     addDirectMem(MIB, X86::RDI);
21012     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21013   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21014     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21015                                       TII->get(X86::MOV32rm), X86::EAX)
21016     .addReg(0)
21017     .addImm(0).addReg(0)
21018     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21019                       MI->getOperand(3).getTargetFlags())
21020     .addReg(0);
21021     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21022     addDirectMem(MIB, X86::EAX);
21023     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21024   } else {
21025     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21026                                       TII->get(X86::MOV32rm), X86::EAX)
21027     .addReg(TII->getGlobalBaseReg(F))
21028     .addImm(0).addReg(0)
21029     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21030                       MI->getOperand(3).getTargetFlags())
21031     .addReg(0);
21032     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21033     addDirectMem(MIB, X86::EAX);
21034     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21035   }
21036
21037   MI->eraseFromParent(); // The pseudo instruction is gone now.
21038   return BB;
21039 }
21040
21041 MachineBasicBlock *
21042 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21043                                     MachineBasicBlock *MBB) const {
21044   DebugLoc DL = MI->getDebugLoc();
21045   MachineFunction *MF = MBB->getParent();
21046   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
21047   MachineRegisterInfo &MRI = MF->getRegInfo();
21048
21049   const BasicBlock *BB = MBB->getBasicBlock();
21050   MachineFunction::iterator I = MBB;
21051   ++I;
21052
21053   // Memory Reference
21054   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21055   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21056
21057   unsigned DstReg;
21058   unsigned MemOpndSlot = 0;
21059
21060   unsigned CurOp = 0;
21061
21062   DstReg = MI->getOperand(CurOp++).getReg();
21063   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21064   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21065   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21066   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21067
21068   MemOpndSlot = CurOp;
21069
21070   MVT PVT = getPointerTy();
21071   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21072          "Invalid Pointer Size!");
21073
21074   // For v = setjmp(buf), we generate
21075   //
21076   // thisMBB:
21077   //  buf[LabelOffset] = restoreMBB
21078   //  SjLjSetup restoreMBB
21079   //
21080   // mainMBB:
21081   //  v_main = 0
21082   //
21083   // sinkMBB:
21084   //  v = phi(main, restore)
21085   //
21086   // restoreMBB:
21087   //  if base pointer being used, load it from frame
21088   //  v_restore = 1
21089
21090   MachineBasicBlock *thisMBB = MBB;
21091   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21092   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21093   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21094   MF->insert(I, mainMBB);
21095   MF->insert(I, sinkMBB);
21096   MF->push_back(restoreMBB);
21097
21098   MachineInstrBuilder MIB;
21099
21100   // Transfer the remainder of BB and its successor edges to sinkMBB.
21101   sinkMBB->splice(sinkMBB->begin(), MBB,
21102                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21103   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21104
21105   // thisMBB:
21106   unsigned PtrStoreOpc = 0;
21107   unsigned LabelReg = 0;
21108   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21109   Reloc::Model RM = MF->getTarget().getRelocationModel();
21110   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21111                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21112
21113   // Prepare IP either in reg or imm.
21114   if (!UseImmLabel) {
21115     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21116     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21117     LabelReg = MRI.createVirtualRegister(PtrRC);
21118     if (Subtarget->is64Bit()) {
21119       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21120               .addReg(X86::RIP)
21121               .addImm(0)
21122               .addReg(0)
21123               .addMBB(restoreMBB)
21124               .addReg(0);
21125     } else {
21126       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21127       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21128               .addReg(XII->getGlobalBaseReg(MF))
21129               .addImm(0)
21130               .addReg(0)
21131               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21132               .addReg(0);
21133     }
21134   } else
21135     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21136   // Store IP
21137   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21138   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21139     if (i == X86::AddrDisp)
21140       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21141     else
21142       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21143   }
21144   if (!UseImmLabel)
21145     MIB.addReg(LabelReg);
21146   else
21147     MIB.addMBB(restoreMBB);
21148   MIB.setMemRefs(MMOBegin, MMOEnd);
21149   // Setup
21150   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21151           .addMBB(restoreMBB);
21152
21153   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
21154       MF->getSubtarget().getRegisterInfo());
21155   MIB.addRegMask(RegInfo->getNoPreservedMask());
21156   thisMBB->addSuccessor(mainMBB);
21157   thisMBB->addSuccessor(restoreMBB);
21158
21159   // mainMBB:
21160   //  EAX = 0
21161   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21162   mainMBB->addSuccessor(sinkMBB);
21163
21164   // sinkMBB:
21165   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21166           TII->get(X86::PHI), DstReg)
21167     .addReg(mainDstReg).addMBB(mainMBB)
21168     .addReg(restoreDstReg).addMBB(restoreMBB);
21169
21170   // restoreMBB:
21171   if (RegInfo->hasBasePointer(*MF)) {
21172     const X86Subtarget &STI = MF->getTarget().getSubtarget<X86Subtarget>();
21173     const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
21174     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21175     X86FI->setRestoreBasePointer(MF);
21176     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21177     unsigned BasePtr = RegInfo->getBaseRegister();
21178     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21179     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21180                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21181       .setMIFlag(MachineInstr::FrameSetup);
21182   }
21183   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21184   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21185   restoreMBB->addSuccessor(sinkMBB);
21186
21187   MI->eraseFromParent();
21188   return sinkMBB;
21189 }
21190
21191 MachineBasicBlock *
21192 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21193                                      MachineBasicBlock *MBB) const {
21194   DebugLoc DL = MI->getDebugLoc();
21195   MachineFunction *MF = MBB->getParent();
21196   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
21197   MachineRegisterInfo &MRI = MF->getRegInfo();
21198
21199   // Memory Reference
21200   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21201   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21202
21203   MVT PVT = getPointerTy();
21204   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21205          "Invalid Pointer Size!");
21206
21207   const TargetRegisterClass *RC =
21208     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21209   unsigned Tmp = MRI.createVirtualRegister(RC);
21210   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21211   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
21212       MF->getSubtarget().getRegisterInfo());
21213   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21214   unsigned SP = RegInfo->getStackRegister();
21215
21216   MachineInstrBuilder MIB;
21217
21218   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21219   const int64_t SPOffset = 2 * PVT.getStoreSize();
21220
21221   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21222   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21223
21224   // Reload FP
21225   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21226   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21227     MIB.addOperand(MI->getOperand(i));
21228   MIB.setMemRefs(MMOBegin, MMOEnd);
21229   // Reload IP
21230   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21231   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21232     if (i == X86::AddrDisp)
21233       MIB.addDisp(MI->getOperand(i), LabelOffset);
21234     else
21235       MIB.addOperand(MI->getOperand(i));
21236   }
21237   MIB.setMemRefs(MMOBegin, MMOEnd);
21238   // Reload SP
21239   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21240   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21241     if (i == X86::AddrDisp)
21242       MIB.addDisp(MI->getOperand(i), SPOffset);
21243     else
21244       MIB.addOperand(MI->getOperand(i));
21245   }
21246   MIB.setMemRefs(MMOBegin, MMOEnd);
21247   // Jump
21248   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21249
21250   MI->eraseFromParent();
21251   return MBB;
21252 }
21253
21254 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21255 // accumulator loops. Writing back to the accumulator allows the coalescer
21256 // to remove extra copies in the loop.
21257 MachineBasicBlock *
21258 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21259                                  MachineBasicBlock *MBB) const {
21260   MachineOperand &AddendOp = MI->getOperand(3);
21261
21262   // Bail out early if the addend isn't a register - we can't switch these.
21263   if (!AddendOp.isReg())
21264     return MBB;
21265
21266   MachineFunction &MF = *MBB->getParent();
21267   MachineRegisterInfo &MRI = MF.getRegInfo();
21268
21269   // Check whether the addend is defined by a PHI:
21270   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21271   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21272   if (!AddendDef.isPHI())
21273     return MBB;
21274
21275   // Look for the following pattern:
21276   // loop:
21277   //   %addend = phi [%entry, 0], [%loop, %result]
21278   //   ...
21279   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21280
21281   // Replace with:
21282   //   loop:
21283   //   %addend = phi [%entry, 0], [%loop, %result]
21284   //   ...
21285   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21286
21287   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21288     assert(AddendDef.getOperand(i).isReg());
21289     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21290     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21291     if (&PHISrcInst == MI) {
21292       // Found a matching instruction.
21293       unsigned NewFMAOpc = 0;
21294       switch (MI->getOpcode()) {
21295         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21296         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21297         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21298         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21299         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21300         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21301         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21302         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21303         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21304         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21305         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21306         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21307         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21308         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21309         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21310         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21311         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21312         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21313         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21314         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21315
21316         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21317         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21318         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21319         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21320         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21321         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21322         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21323         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21324         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21325         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21326         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21327         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21328         default: llvm_unreachable("Unrecognized FMA variant.");
21329       }
21330
21331       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
21332       MachineInstrBuilder MIB =
21333         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21334         .addOperand(MI->getOperand(0))
21335         .addOperand(MI->getOperand(3))
21336         .addOperand(MI->getOperand(2))
21337         .addOperand(MI->getOperand(1));
21338       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21339       MI->eraseFromParent();
21340     }
21341   }
21342
21343   return MBB;
21344 }
21345
21346 MachineBasicBlock *
21347 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21348                                                MachineBasicBlock *BB) const {
21349   switch (MI->getOpcode()) {
21350   default: llvm_unreachable("Unexpected instr type to insert");
21351   case X86::TAILJMPd64:
21352   case X86::TAILJMPr64:
21353   case X86::TAILJMPm64:
21354     llvm_unreachable("TAILJMP64 would not be touched here.");
21355   case X86::TCRETURNdi64:
21356   case X86::TCRETURNri64:
21357   case X86::TCRETURNmi64:
21358     return BB;
21359   case X86::WIN_ALLOCA:
21360     return EmitLoweredWinAlloca(MI, BB);
21361   case X86::SEG_ALLOCA_32:
21362   case X86::SEG_ALLOCA_64:
21363     return EmitLoweredSegAlloca(MI, BB);
21364   case X86::TLSCall_32:
21365   case X86::TLSCall_64:
21366     return EmitLoweredTLSCall(MI, BB);
21367   case X86::CMOV_GR8:
21368   case X86::CMOV_FR32:
21369   case X86::CMOV_FR64:
21370   case X86::CMOV_V4F32:
21371   case X86::CMOV_V2F64:
21372   case X86::CMOV_V2I64:
21373   case X86::CMOV_V8F32:
21374   case X86::CMOV_V4F64:
21375   case X86::CMOV_V4I64:
21376   case X86::CMOV_V16F32:
21377   case X86::CMOV_V8F64:
21378   case X86::CMOV_V8I64:
21379   case X86::CMOV_GR16:
21380   case X86::CMOV_GR32:
21381   case X86::CMOV_RFP32:
21382   case X86::CMOV_RFP64:
21383   case X86::CMOV_RFP80:
21384     return EmitLoweredSelect(MI, BB);
21385
21386   case X86::FP32_TO_INT16_IN_MEM:
21387   case X86::FP32_TO_INT32_IN_MEM:
21388   case X86::FP32_TO_INT64_IN_MEM:
21389   case X86::FP64_TO_INT16_IN_MEM:
21390   case X86::FP64_TO_INT32_IN_MEM:
21391   case X86::FP64_TO_INT64_IN_MEM:
21392   case X86::FP80_TO_INT16_IN_MEM:
21393   case X86::FP80_TO_INT32_IN_MEM:
21394   case X86::FP80_TO_INT64_IN_MEM: {
21395     MachineFunction *F = BB->getParent();
21396     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
21397     DebugLoc DL = MI->getDebugLoc();
21398
21399     // Change the floating point control register to use "round towards zero"
21400     // mode when truncating to an integer value.
21401     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21402     addFrameReference(BuildMI(*BB, MI, DL,
21403                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21404
21405     // Load the old value of the high byte of the control word...
21406     unsigned OldCW =
21407       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21408     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21409                       CWFrameIdx);
21410
21411     // Set the high part to be round to zero...
21412     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21413       .addImm(0xC7F);
21414
21415     // Reload the modified control word now...
21416     addFrameReference(BuildMI(*BB, MI, DL,
21417                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21418
21419     // Restore the memory image of control word to original value
21420     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21421       .addReg(OldCW);
21422
21423     // Get the X86 opcode to use.
21424     unsigned Opc;
21425     switch (MI->getOpcode()) {
21426     default: llvm_unreachable("illegal opcode!");
21427     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21428     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21429     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21430     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21431     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21432     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21433     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21434     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21435     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21436     }
21437
21438     X86AddressMode AM;
21439     MachineOperand &Op = MI->getOperand(0);
21440     if (Op.isReg()) {
21441       AM.BaseType = X86AddressMode::RegBase;
21442       AM.Base.Reg = Op.getReg();
21443     } else {
21444       AM.BaseType = X86AddressMode::FrameIndexBase;
21445       AM.Base.FrameIndex = Op.getIndex();
21446     }
21447     Op = MI->getOperand(1);
21448     if (Op.isImm())
21449       AM.Scale = Op.getImm();
21450     Op = MI->getOperand(2);
21451     if (Op.isImm())
21452       AM.IndexReg = Op.getImm();
21453     Op = MI->getOperand(3);
21454     if (Op.isGlobal()) {
21455       AM.GV = Op.getGlobal();
21456     } else {
21457       AM.Disp = Op.getImm();
21458     }
21459     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21460                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21461
21462     // Reload the original control word now.
21463     addFrameReference(BuildMI(*BB, MI, DL,
21464                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21465
21466     MI->eraseFromParent();   // The pseudo instruction is gone now.
21467     return BB;
21468   }
21469     // String/text processing lowering.
21470   case X86::PCMPISTRM128REG:
21471   case X86::VPCMPISTRM128REG:
21472   case X86::PCMPISTRM128MEM:
21473   case X86::VPCMPISTRM128MEM:
21474   case X86::PCMPESTRM128REG:
21475   case X86::VPCMPESTRM128REG:
21476   case X86::PCMPESTRM128MEM:
21477   case X86::VPCMPESTRM128MEM:
21478     assert(Subtarget->hasSSE42() &&
21479            "Target must have SSE4.2 or AVX features enabled");
21480     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21481
21482   // String/text processing lowering.
21483   case X86::PCMPISTRIREG:
21484   case X86::VPCMPISTRIREG:
21485   case X86::PCMPISTRIMEM:
21486   case X86::VPCMPISTRIMEM:
21487   case X86::PCMPESTRIREG:
21488   case X86::VPCMPESTRIREG:
21489   case X86::PCMPESTRIMEM:
21490   case X86::VPCMPESTRIMEM:
21491     assert(Subtarget->hasSSE42() &&
21492            "Target must have SSE4.2 or AVX features enabled");
21493     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21494
21495   // Thread synchronization.
21496   case X86::MONITOR:
21497     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
21498                        Subtarget);
21499
21500   // xbegin
21501   case X86::XBEGIN:
21502     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21503
21504   case X86::VASTART_SAVE_XMM_REGS:
21505     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21506
21507   case X86::VAARG_64:
21508     return EmitVAARG64WithCustomInserter(MI, BB);
21509
21510   case X86::EH_SjLj_SetJmp32:
21511   case X86::EH_SjLj_SetJmp64:
21512     return emitEHSjLjSetJmp(MI, BB);
21513
21514   case X86::EH_SjLj_LongJmp32:
21515   case X86::EH_SjLj_LongJmp64:
21516     return emitEHSjLjLongJmp(MI, BB);
21517
21518   case TargetOpcode::STATEPOINT:
21519     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21520     // this point in the process.  We diverge later.
21521     return emitPatchPoint(MI, BB);
21522
21523   case TargetOpcode::STACKMAP:
21524   case TargetOpcode::PATCHPOINT:
21525     return emitPatchPoint(MI, BB);
21526
21527   case X86::VFMADDPDr213r:
21528   case X86::VFMADDPSr213r:
21529   case X86::VFMADDSDr213r:
21530   case X86::VFMADDSSr213r:
21531   case X86::VFMSUBPDr213r:
21532   case X86::VFMSUBPSr213r:
21533   case X86::VFMSUBSDr213r:
21534   case X86::VFMSUBSSr213r:
21535   case X86::VFNMADDPDr213r:
21536   case X86::VFNMADDPSr213r:
21537   case X86::VFNMADDSDr213r:
21538   case X86::VFNMADDSSr213r:
21539   case X86::VFNMSUBPDr213r:
21540   case X86::VFNMSUBPSr213r:
21541   case X86::VFNMSUBSDr213r:
21542   case X86::VFNMSUBSSr213r:
21543   case X86::VFMADDSUBPDr213r:
21544   case X86::VFMADDSUBPSr213r:
21545   case X86::VFMSUBADDPDr213r:
21546   case X86::VFMSUBADDPSr213r:
21547   case X86::VFMADDPDr213rY:
21548   case X86::VFMADDPSr213rY:
21549   case X86::VFMSUBPDr213rY:
21550   case X86::VFMSUBPSr213rY:
21551   case X86::VFNMADDPDr213rY:
21552   case X86::VFNMADDPSr213rY:
21553   case X86::VFNMSUBPDr213rY:
21554   case X86::VFNMSUBPSr213rY:
21555   case X86::VFMADDSUBPDr213rY:
21556   case X86::VFMADDSUBPSr213rY:
21557   case X86::VFMSUBADDPDr213rY:
21558   case X86::VFMSUBADDPSr213rY:
21559     return emitFMA3Instr(MI, BB);
21560   }
21561 }
21562
21563 //===----------------------------------------------------------------------===//
21564 //                           X86 Optimization Hooks
21565 //===----------------------------------------------------------------------===//
21566
21567 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21568                                                       APInt &KnownZero,
21569                                                       APInt &KnownOne,
21570                                                       const SelectionDAG &DAG,
21571                                                       unsigned Depth) const {
21572   unsigned BitWidth = KnownZero.getBitWidth();
21573   unsigned Opc = Op.getOpcode();
21574   assert((Opc >= ISD::BUILTIN_OP_END ||
21575           Opc == ISD::INTRINSIC_WO_CHAIN ||
21576           Opc == ISD::INTRINSIC_W_CHAIN ||
21577           Opc == ISD::INTRINSIC_VOID) &&
21578          "Should use MaskedValueIsZero if you don't know whether Op"
21579          " is a target node!");
21580
21581   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21582   switch (Opc) {
21583   default: break;
21584   case X86ISD::ADD:
21585   case X86ISD::SUB:
21586   case X86ISD::ADC:
21587   case X86ISD::SBB:
21588   case X86ISD::SMUL:
21589   case X86ISD::UMUL:
21590   case X86ISD::INC:
21591   case X86ISD::DEC:
21592   case X86ISD::OR:
21593   case X86ISD::XOR:
21594   case X86ISD::AND:
21595     // These nodes' second result is a boolean.
21596     if (Op.getResNo() == 0)
21597       break;
21598     // Fallthrough
21599   case X86ISD::SETCC:
21600     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21601     break;
21602   case ISD::INTRINSIC_WO_CHAIN: {
21603     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21604     unsigned NumLoBits = 0;
21605     switch (IntId) {
21606     default: break;
21607     case Intrinsic::x86_sse_movmsk_ps:
21608     case Intrinsic::x86_avx_movmsk_ps_256:
21609     case Intrinsic::x86_sse2_movmsk_pd:
21610     case Intrinsic::x86_avx_movmsk_pd_256:
21611     case Intrinsic::x86_mmx_pmovmskb:
21612     case Intrinsic::x86_sse2_pmovmskb_128:
21613     case Intrinsic::x86_avx2_pmovmskb: {
21614       // High bits of movmskp{s|d}, pmovmskb are known zero.
21615       switch (IntId) {
21616         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21617         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21618         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21619         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21620         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21621         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21622         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21623         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21624       }
21625       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21626       break;
21627     }
21628     }
21629     break;
21630   }
21631   }
21632 }
21633
21634 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21635   SDValue Op,
21636   const SelectionDAG &,
21637   unsigned Depth) const {
21638   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21639   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21640     return Op.getValueType().getScalarType().getSizeInBits();
21641
21642   // Fallback case.
21643   return 1;
21644 }
21645
21646 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21647 /// node is a GlobalAddress + offset.
21648 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21649                                        const GlobalValue* &GA,
21650                                        int64_t &Offset) const {
21651   if (N->getOpcode() == X86ISD::Wrapper) {
21652     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21653       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21654       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21655       return true;
21656     }
21657   }
21658   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21659 }
21660
21661 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21662 /// same as extracting the high 128-bit part of 256-bit vector and then
21663 /// inserting the result into the low part of a new 256-bit vector
21664 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21665   EVT VT = SVOp->getValueType(0);
21666   unsigned NumElems = VT.getVectorNumElements();
21667
21668   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21669   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21670     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21671         SVOp->getMaskElt(j) >= 0)
21672       return false;
21673
21674   return true;
21675 }
21676
21677 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21678 /// same as extracting the low 128-bit part of 256-bit vector and then
21679 /// inserting the result into the high part of a new 256-bit vector
21680 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21681   EVT VT = SVOp->getValueType(0);
21682   unsigned NumElems = VT.getVectorNumElements();
21683
21684   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21685   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21686     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21687         SVOp->getMaskElt(j) >= 0)
21688       return false;
21689
21690   return true;
21691 }
21692
21693 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21694 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21695                                         TargetLowering::DAGCombinerInfo &DCI,
21696                                         const X86Subtarget* Subtarget) {
21697   SDLoc dl(N);
21698   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21699   SDValue V1 = SVOp->getOperand(0);
21700   SDValue V2 = SVOp->getOperand(1);
21701   EVT VT = SVOp->getValueType(0);
21702   unsigned NumElems = VT.getVectorNumElements();
21703
21704   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21705       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21706     //
21707     //                   0,0,0,...
21708     //                      |
21709     //    V      UNDEF    BUILD_VECTOR    UNDEF
21710     //     \      /           \           /
21711     //  CONCAT_VECTOR         CONCAT_VECTOR
21712     //         \                  /
21713     //          \                /
21714     //          RESULT: V + zero extended
21715     //
21716     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21717         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21718         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21719       return SDValue();
21720
21721     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21722       return SDValue();
21723
21724     // To match the shuffle mask, the first half of the mask should
21725     // be exactly the first vector, and all the rest a splat with the
21726     // first element of the second one.
21727     for (unsigned i = 0; i != NumElems/2; ++i)
21728       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21729           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21730         return SDValue();
21731
21732     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21733     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21734       if (Ld->hasNUsesOfValue(1, 0)) {
21735         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21736         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21737         SDValue ResNode =
21738           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21739                                   Ld->getMemoryVT(),
21740                                   Ld->getPointerInfo(),
21741                                   Ld->getAlignment(),
21742                                   false/*isVolatile*/, true/*ReadMem*/,
21743                                   false/*WriteMem*/);
21744
21745         // Make sure the newly-created LOAD is in the same position as Ld in
21746         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21747         // and update uses of Ld's output chain to use the TokenFactor.
21748         if (Ld->hasAnyUseOfValue(1)) {
21749           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21750                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21751           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21752           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21753                                  SDValue(ResNode.getNode(), 1));
21754         }
21755
21756         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
21757       }
21758     }
21759
21760     // Emit a zeroed vector and insert the desired subvector on its
21761     // first half.
21762     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21763     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21764     return DCI.CombineTo(N, InsV);
21765   }
21766
21767   //===--------------------------------------------------------------------===//
21768   // Combine some shuffles into subvector extracts and inserts:
21769   //
21770
21771   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21772   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21773     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21774     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21775     return DCI.CombineTo(N, InsV);
21776   }
21777
21778   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21779   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21780     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21781     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21782     return DCI.CombineTo(N, InsV);
21783   }
21784
21785   return SDValue();
21786 }
21787
21788 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21789 /// possible.
21790 ///
21791 /// This is the leaf of the recursive combinine below. When we have found some
21792 /// chain of single-use x86 shuffle instructions and accumulated the combined
21793 /// shuffle mask represented by them, this will try to pattern match that mask
21794 /// into either a single instruction if there is a special purpose instruction
21795 /// for this operation, or into a PSHUFB instruction which is a fully general
21796 /// instruction but should only be used to replace chains over a certain depth.
21797 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21798                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21799                                    TargetLowering::DAGCombinerInfo &DCI,
21800                                    const X86Subtarget *Subtarget) {
21801   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21802
21803   // Find the operand that enters the chain. Note that multiple uses are OK
21804   // here, we're not going to remove the operand we find.
21805   SDValue Input = Op.getOperand(0);
21806   while (Input.getOpcode() == ISD::BITCAST)
21807     Input = Input.getOperand(0);
21808
21809   MVT VT = Input.getSimpleValueType();
21810   MVT RootVT = Root.getSimpleValueType();
21811   SDLoc DL(Root);
21812
21813   // Just remove no-op shuffle masks.
21814   if (Mask.size() == 1) {
21815     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
21816                   /*AddTo*/ true);
21817     return true;
21818   }
21819
21820   // Use the float domain if the operand type is a floating point type.
21821   bool FloatDomain = VT.isFloatingPoint();
21822
21823   // For floating point shuffles, we don't have free copies in the shuffle
21824   // instructions or the ability to load as part of the instruction, so
21825   // canonicalize their shuffles to UNPCK or MOV variants.
21826   //
21827   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21828   // vectors because it can have a load folded into it that UNPCK cannot. This
21829   // doesn't preclude something switching to the shorter encoding post-RA.
21830   if (FloatDomain) {
21831     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
21832       bool Lo = Mask.equals(0, 0);
21833       unsigned Shuffle;
21834       MVT ShuffleVT;
21835       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21836       // is no slower than UNPCKLPD but has the option to fold the input operand
21837       // into even an unaligned memory load.
21838       if (Lo && Subtarget->hasSSE3()) {
21839         Shuffle = X86ISD::MOVDDUP;
21840         ShuffleVT = MVT::v2f64;
21841       } else {
21842         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21843         // than the UNPCK variants.
21844         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21845         ShuffleVT = MVT::v4f32;
21846       }
21847       if (Depth == 1 && Root->getOpcode() == Shuffle)
21848         return false; // Nothing to do!
21849       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21850       DCI.AddToWorklist(Op.getNode());
21851       if (Shuffle == X86ISD::MOVDDUP)
21852         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21853       else
21854         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21855       DCI.AddToWorklist(Op.getNode());
21856       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21857                     /*AddTo*/ true);
21858       return true;
21859     }
21860     if (Subtarget->hasSSE3() &&
21861         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
21862       bool Lo = Mask.equals(0, 0, 2, 2);
21863       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21864       MVT ShuffleVT = MVT::v4f32;
21865       if (Depth == 1 && Root->getOpcode() == Shuffle)
21866         return false; // Nothing to do!
21867       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21868       DCI.AddToWorklist(Op.getNode());
21869       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21870       DCI.AddToWorklist(Op.getNode());
21871       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21872                     /*AddTo*/ true);
21873       return true;
21874     }
21875     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
21876       bool Lo = Mask.equals(0, 0, 1, 1);
21877       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21878       MVT ShuffleVT = MVT::v4f32;
21879       if (Depth == 1 && Root->getOpcode() == Shuffle)
21880         return false; // Nothing to do!
21881       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21882       DCI.AddToWorklist(Op.getNode());
21883       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21884       DCI.AddToWorklist(Op.getNode());
21885       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21886                     /*AddTo*/ true);
21887       return true;
21888     }
21889   }
21890
21891   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21892   // variants as none of these have single-instruction variants that are
21893   // superior to the UNPCK formulation.
21894   if (!FloatDomain &&
21895       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
21896        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
21897        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
21898        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
21899                    15))) {
21900     bool Lo = Mask[0] == 0;
21901     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21902     if (Depth == 1 && Root->getOpcode() == Shuffle)
21903       return false; // Nothing to do!
21904     MVT ShuffleVT;
21905     switch (Mask.size()) {
21906     case 8:
21907       ShuffleVT = MVT::v8i16;
21908       break;
21909     case 16:
21910       ShuffleVT = MVT::v16i8;
21911       break;
21912     default:
21913       llvm_unreachable("Impossible mask size!");
21914     };
21915     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21916     DCI.AddToWorklist(Op.getNode());
21917     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21918     DCI.AddToWorklist(Op.getNode());
21919     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21920                   /*AddTo*/ true);
21921     return true;
21922   }
21923
21924   // Don't try to re-form single instruction chains under any circumstances now
21925   // that we've done encoding canonicalization for them.
21926   if (Depth < 2)
21927     return false;
21928
21929   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21930   // can replace them with a single PSHUFB instruction profitably. Intel's
21931   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21932   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21933   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21934     SmallVector<SDValue, 16> PSHUFBMask;
21935     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
21936     int Ratio = 16 / Mask.size();
21937     for (unsigned i = 0; i < 16; ++i) {
21938       if (Mask[i / Ratio] == SM_SentinelUndef) {
21939         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21940         continue;
21941       }
21942       int M = Mask[i / Ratio] != SM_SentinelZero
21943                   ? Ratio * Mask[i / Ratio] + i % Ratio
21944                   : 255;
21945       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
21946     }
21947     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
21948     DCI.AddToWorklist(Op.getNode());
21949     SDValue PSHUFBMaskOp =
21950         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
21951     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21952     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
21953     DCI.AddToWorklist(Op.getNode());
21954     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21955                   /*AddTo*/ true);
21956     return true;
21957   }
21958
21959   // Failed to find any combines.
21960   return false;
21961 }
21962
21963 /// \brief Fully generic combining of x86 shuffle instructions.
21964 ///
21965 /// This should be the last combine run over the x86 shuffle instructions. Once
21966 /// they have been fully optimized, this will recursively consider all chains
21967 /// of single-use shuffle instructions, build a generic model of the cumulative
21968 /// shuffle operation, and check for simpler instructions which implement this
21969 /// operation. We use this primarily for two purposes:
21970 ///
21971 /// 1) Collapse generic shuffles to specialized single instructions when
21972 ///    equivalent. In most cases, this is just an encoding size win, but
21973 ///    sometimes we will collapse multiple generic shuffles into a single
21974 ///    special-purpose shuffle.
21975 /// 2) Look for sequences of shuffle instructions with 3 or more total
21976 ///    instructions, and replace them with the slightly more expensive SSSE3
21977 ///    PSHUFB instruction if available. We do this as the last combining step
21978 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21979 ///    a suitable short sequence of other instructions. The PHUFB will either
21980 ///    use a register or have to read from memory and so is slightly (but only
21981 ///    slightly) more expensive than the other shuffle instructions.
21982 ///
21983 /// Because this is inherently a quadratic operation (for each shuffle in
21984 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21985 /// This should never be an issue in practice as the shuffle lowering doesn't
21986 /// produce sequences of more than 8 instructions.
21987 ///
21988 /// FIXME: We will currently miss some cases where the redundant shuffling
21989 /// would simplify under the threshold for PSHUFB formation because of
21990 /// combine-ordering. To fix this, we should do the redundant instruction
21991 /// combining in this recursive walk.
21992 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21993                                           ArrayRef<int> RootMask,
21994                                           int Depth, bool HasPSHUFB,
21995                                           SelectionDAG &DAG,
21996                                           TargetLowering::DAGCombinerInfo &DCI,
21997                                           const X86Subtarget *Subtarget) {
21998   // Bound the depth of our recursive combine because this is ultimately
21999   // quadratic in nature.
22000   if (Depth > 8)
22001     return false;
22002
22003   // Directly rip through bitcasts to find the underlying operand.
22004   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22005     Op = Op.getOperand(0);
22006
22007   MVT VT = Op.getSimpleValueType();
22008   if (!VT.isVector())
22009     return false; // Bail if we hit a non-vector.
22010   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
22011   // version should be added.
22012   if (VT.getSizeInBits() != 128)
22013     return false;
22014
22015   assert(Root.getSimpleValueType().isVector() &&
22016          "Shuffles operate on vector types!");
22017   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22018          "Can only combine shuffles of the same vector register size.");
22019
22020   if (!isTargetShuffle(Op.getOpcode()))
22021     return false;
22022   SmallVector<int, 16> OpMask;
22023   bool IsUnary;
22024   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22025   // We only can combine unary shuffles which we can decode the mask for.
22026   if (!HaveMask || !IsUnary)
22027     return false;
22028
22029   assert(VT.getVectorNumElements() == OpMask.size() &&
22030          "Different mask size from vector size!");
22031   assert(((RootMask.size() > OpMask.size() &&
22032            RootMask.size() % OpMask.size() == 0) ||
22033           (OpMask.size() > RootMask.size() &&
22034            OpMask.size() % RootMask.size() == 0) ||
22035           OpMask.size() == RootMask.size()) &&
22036          "The smaller number of elements must divide the larger.");
22037   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22038   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22039   assert(((RootRatio == 1 && OpRatio == 1) ||
22040           (RootRatio == 1) != (OpRatio == 1)) &&
22041          "Must not have a ratio for both incoming and op masks!");
22042
22043   SmallVector<int, 16> Mask;
22044   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22045
22046   // Merge this shuffle operation's mask into our accumulated mask. Note that
22047   // this shuffle's mask will be the first applied to the input, followed by the
22048   // root mask to get us all the way to the root value arrangement. The reason
22049   // for this order is that we are recursing up the operation chain.
22050   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22051     int RootIdx = i / RootRatio;
22052     if (RootMask[RootIdx] < 0) {
22053       // This is a zero or undef lane, we're done.
22054       Mask.push_back(RootMask[RootIdx]);
22055       continue;
22056     }
22057
22058     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22059     int OpIdx = RootMaskedIdx / OpRatio;
22060     if (OpMask[OpIdx] < 0) {
22061       // The incoming lanes are zero or undef, it doesn't matter which ones we
22062       // are using.
22063       Mask.push_back(OpMask[OpIdx]);
22064       continue;
22065     }
22066
22067     // Ok, we have non-zero lanes, map them through.
22068     Mask.push_back(OpMask[OpIdx] * OpRatio +
22069                    RootMaskedIdx % OpRatio);
22070   }
22071
22072   // See if we can recurse into the operand to combine more things.
22073   switch (Op.getOpcode()) {
22074     case X86ISD::PSHUFB:
22075       HasPSHUFB = true;
22076     case X86ISD::PSHUFD:
22077     case X86ISD::PSHUFHW:
22078     case X86ISD::PSHUFLW:
22079       if (Op.getOperand(0).hasOneUse() &&
22080           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22081                                         HasPSHUFB, DAG, DCI, Subtarget))
22082         return true;
22083       break;
22084
22085     case X86ISD::UNPCKL:
22086     case X86ISD::UNPCKH:
22087       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
22088       // We can't check for single use, we have to check that this shuffle is the only user.
22089       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22090           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22091                                         HasPSHUFB, DAG, DCI, Subtarget))
22092           return true;
22093       break;
22094   }
22095
22096   // Minor canonicalization of the accumulated shuffle mask to make it easier
22097   // to match below. All this does is detect masks with squential pairs of
22098   // elements, and shrink them to the half-width mask. It does this in a loop
22099   // so it will reduce the size of the mask to the minimal width mask which
22100   // performs an equivalent shuffle.
22101   SmallVector<int, 16> WidenedMask;
22102   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22103     Mask = std::move(WidenedMask);
22104     WidenedMask.clear();
22105   }
22106
22107   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22108                                 Subtarget);
22109 }
22110
22111 /// \brief Get the PSHUF-style mask from PSHUF node.
22112 ///
22113 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22114 /// PSHUF-style masks that can be reused with such instructions.
22115 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22116   SmallVector<int, 4> Mask;
22117   bool IsUnary;
22118   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
22119   (void)HaveMask;
22120   assert(HaveMask);
22121
22122   switch (N.getOpcode()) {
22123   case X86ISD::PSHUFD:
22124     return Mask;
22125   case X86ISD::PSHUFLW:
22126     Mask.resize(4);
22127     return Mask;
22128   case X86ISD::PSHUFHW:
22129     Mask.erase(Mask.begin(), Mask.begin() + 4);
22130     for (int &M : Mask)
22131       M -= 4;
22132     return Mask;
22133   default:
22134     llvm_unreachable("No valid shuffle instruction found!");
22135   }
22136 }
22137
22138 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22139 ///
22140 /// We walk up the chain and look for a combinable shuffle, skipping over
22141 /// shuffles that we could hoist this shuffle's transformation past without
22142 /// altering anything.
22143 static SDValue
22144 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22145                              SelectionDAG &DAG,
22146                              TargetLowering::DAGCombinerInfo &DCI) {
22147   assert(N.getOpcode() == X86ISD::PSHUFD &&
22148          "Called with something other than an x86 128-bit half shuffle!");
22149   SDLoc DL(N);
22150
22151   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22152   // of the shuffles in the chain so that we can form a fresh chain to replace
22153   // this one.
22154   SmallVector<SDValue, 8> Chain;
22155   SDValue V = N.getOperand(0);
22156   for (; V.hasOneUse(); V = V.getOperand(0)) {
22157     switch (V.getOpcode()) {
22158     default:
22159       return SDValue(); // Nothing combined!
22160
22161     case ISD::BITCAST:
22162       // Skip bitcasts as we always know the type for the target specific
22163       // instructions.
22164       continue;
22165
22166     case X86ISD::PSHUFD:
22167       // Found another dword shuffle.
22168       break;
22169
22170     case X86ISD::PSHUFLW:
22171       // Check that the low words (being shuffled) are the identity in the
22172       // dword shuffle, and the high words are self-contained.
22173       if (Mask[0] != 0 || Mask[1] != 1 ||
22174           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22175         return SDValue();
22176
22177       Chain.push_back(V);
22178       continue;
22179
22180     case X86ISD::PSHUFHW:
22181       // Check that the high words (being shuffled) are the identity in the
22182       // dword shuffle, and the low words are self-contained.
22183       if (Mask[2] != 2 || Mask[3] != 3 ||
22184           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22185         return SDValue();
22186
22187       Chain.push_back(V);
22188       continue;
22189
22190     case X86ISD::UNPCKL:
22191     case X86ISD::UNPCKH:
22192       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22193       // shuffle into a preceding word shuffle.
22194       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
22195         return SDValue();
22196
22197       // Search for a half-shuffle which we can combine with.
22198       unsigned CombineOp =
22199           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22200       if (V.getOperand(0) != V.getOperand(1) ||
22201           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22202         return SDValue();
22203       Chain.push_back(V);
22204       V = V.getOperand(0);
22205       do {
22206         switch (V.getOpcode()) {
22207         default:
22208           return SDValue(); // Nothing to combine.
22209
22210         case X86ISD::PSHUFLW:
22211         case X86ISD::PSHUFHW:
22212           if (V.getOpcode() == CombineOp)
22213             break;
22214
22215           Chain.push_back(V);
22216
22217           // Fallthrough!
22218         case ISD::BITCAST:
22219           V = V.getOperand(0);
22220           continue;
22221         }
22222         break;
22223       } while (V.hasOneUse());
22224       break;
22225     }
22226     // Break out of the loop if we break out of the switch.
22227     break;
22228   }
22229
22230   if (!V.hasOneUse())
22231     // We fell out of the loop without finding a viable combining instruction.
22232     return SDValue();
22233
22234   // Merge this node's mask and our incoming mask.
22235   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22236   for (int &M : Mask)
22237     M = VMask[M];
22238   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22239                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22240
22241   // Rebuild the chain around this new shuffle.
22242   while (!Chain.empty()) {
22243     SDValue W = Chain.pop_back_val();
22244
22245     if (V.getValueType() != W.getOperand(0).getValueType())
22246       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
22247
22248     switch (W.getOpcode()) {
22249     default:
22250       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22251
22252     case X86ISD::UNPCKL:
22253     case X86ISD::UNPCKH:
22254       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22255       break;
22256
22257     case X86ISD::PSHUFD:
22258     case X86ISD::PSHUFLW:
22259     case X86ISD::PSHUFHW:
22260       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22261       break;
22262     }
22263   }
22264   if (V.getValueType() != N.getValueType())
22265     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
22266
22267   // Return the new chain to replace N.
22268   return V;
22269 }
22270
22271 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22272 ///
22273 /// We walk up the chain, skipping shuffles of the other half and looking
22274 /// through shuffles which switch halves trying to find a shuffle of the same
22275 /// pair of dwords.
22276 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22277                                         SelectionDAG &DAG,
22278                                         TargetLowering::DAGCombinerInfo &DCI) {
22279   assert(
22280       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22281       "Called with something other than an x86 128-bit half shuffle!");
22282   SDLoc DL(N);
22283   unsigned CombineOpcode = N.getOpcode();
22284
22285   // Walk up a single-use chain looking for a combinable shuffle.
22286   SDValue V = N.getOperand(0);
22287   for (; V.hasOneUse(); V = V.getOperand(0)) {
22288     switch (V.getOpcode()) {
22289     default:
22290       return false; // Nothing combined!
22291
22292     case ISD::BITCAST:
22293       // Skip bitcasts as we always know the type for the target specific
22294       // instructions.
22295       continue;
22296
22297     case X86ISD::PSHUFLW:
22298     case X86ISD::PSHUFHW:
22299       if (V.getOpcode() == CombineOpcode)
22300         break;
22301
22302       // Other-half shuffles are no-ops.
22303       continue;
22304     }
22305     // Break out of the loop if we break out of the switch.
22306     break;
22307   }
22308
22309   if (!V.hasOneUse())
22310     // We fell out of the loop without finding a viable combining instruction.
22311     return false;
22312
22313   // Combine away the bottom node as its shuffle will be accumulated into
22314   // a preceding shuffle.
22315   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22316
22317   // Record the old value.
22318   SDValue Old = V;
22319
22320   // Merge this node's mask and our incoming mask (adjusted to account for all
22321   // the pshufd instructions encountered).
22322   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22323   for (int &M : Mask)
22324     M = VMask[M];
22325   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22326                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22327
22328   // Check that the shuffles didn't cancel each other out. If not, we need to
22329   // combine to the new one.
22330   if (Old != V)
22331     // Replace the combinable shuffle with the combined one, updating all users
22332     // so that we re-evaluate the chain here.
22333     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22334
22335   return true;
22336 }
22337
22338 /// \brief Try to combine x86 target specific shuffles.
22339 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22340                                            TargetLowering::DAGCombinerInfo &DCI,
22341                                            const X86Subtarget *Subtarget) {
22342   SDLoc DL(N);
22343   MVT VT = N.getSimpleValueType();
22344   SmallVector<int, 4> Mask;
22345
22346   switch (N.getOpcode()) {
22347   case X86ISD::PSHUFD:
22348   case X86ISD::PSHUFLW:
22349   case X86ISD::PSHUFHW:
22350     Mask = getPSHUFShuffleMask(N);
22351     assert(Mask.size() == 4);
22352     break;
22353   default:
22354     return SDValue();
22355   }
22356
22357   // Nuke no-op shuffles that show up after combining.
22358   if (isNoopShuffleMask(Mask))
22359     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22360
22361   // Look for simplifications involving one or two shuffle instructions.
22362   SDValue V = N.getOperand(0);
22363   switch (N.getOpcode()) {
22364   default:
22365     break;
22366   case X86ISD::PSHUFLW:
22367   case X86ISD::PSHUFHW:
22368     assert(VT == MVT::v8i16);
22369     (void)VT;
22370
22371     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22372       return SDValue(); // We combined away this shuffle, so we're done.
22373
22374     // See if this reduces to a PSHUFD which is no more expensive and can
22375     // combine with more operations. Note that it has to at least flip the
22376     // dwords as otherwise it would have been removed as a no-op.
22377     if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
22378       int DMask[] = {0, 1, 2, 3};
22379       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22380       DMask[DOffset + 0] = DOffset + 1;
22381       DMask[DOffset + 1] = DOffset + 0;
22382       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
22383       DCI.AddToWorklist(V.getNode());
22384       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
22385                       getV4X86ShuffleImm8ForMask(DMask, DAG));
22386       DCI.AddToWorklist(V.getNode());
22387       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
22388     }
22389
22390     // Look for shuffle patterns which can be implemented as a single unpack.
22391     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22392     // only works when we have a PSHUFD followed by two half-shuffles.
22393     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22394         (V.getOpcode() == X86ISD::PSHUFLW ||
22395          V.getOpcode() == X86ISD::PSHUFHW) &&
22396         V.getOpcode() != N.getOpcode() &&
22397         V.hasOneUse()) {
22398       SDValue D = V.getOperand(0);
22399       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22400         D = D.getOperand(0);
22401       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22402         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22403         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22404         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22405         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22406         int WordMask[8];
22407         for (int i = 0; i < 4; ++i) {
22408           WordMask[i + NOffset] = Mask[i] + NOffset;
22409           WordMask[i + VOffset] = VMask[i] + VOffset;
22410         }
22411         // Map the word mask through the DWord mask.
22412         int MappedMask[8];
22413         for (int i = 0; i < 8; ++i)
22414           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22415         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
22416         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
22417         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
22418                        std::begin(UnpackLoMask)) ||
22419             std::equal(std::begin(MappedMask), std::end(MappedMask),
22420                        std::begin(UnpackHiMask))) {
22421           // We can replace all three shuffles with an unpack.
22422           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
22423           DCI.AddToWorklist(V.getNode());
22424           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22425                                                 : X86ISD::UNPCKH,
22426                              DL, MVT::v8i16, V, V);
22427         }
22428       }
22429     }
22430
22431     break;
22432
22433   case X86ISD::PSHUFD:
22434     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22435       return NewN;
22436
22437     break;
22438   }
22439
22440   return SDValue();
22441 }
22442
22443 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22444 ///
22445 /// We combine this directly on the abstract vector shuffle nodes so it is
22446 /// easier to generically match. We also insert dummy vector shuffle nodes for
22447 /// the operands which explicitly discard the lanes which are unused by this
22448 /// operation to try to flow through the rest of the combiner the fact that
22449 /// they're unused.
22450 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22451   SDLoc DL(N);
22452   EVT VT = N->getValueType(0);
22453
22454   // We only handle target-independent shuffles.
22455   // FIXME: It would be easy and harmless to use the target shuffle mask
22456   // extraction tool to support more.
22457   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22458     return SDValue();
22459
22460   auto *SVN = cast<ShuffleVectorSDNode>(N);
22461   ArrayRef<int> Mask = SVN->getMask();
22462   SDValue V1 = N->getOperand(0);
22463   SDValue V2 = N->getOperand(1);
22464
22465   // We require the first shuffle operand to be the SUB node, and the second to
22466   // be the ADD node.
22467   // FIXME: We should support the commuted patterns.
22468   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22469     return SDValue();
22470
22471   // If there are other uses of these operations we can't fold them.
22472   if (!V1->hasOneUse() || !V2->hasOneUse())
22473     return SDValue();
22474
22475   // Ensure that both operations have the same operands. Note that we can
22476   // commute the FADD operands.
22477   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22478   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22479       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22480     return SDValue();
22481
22482   // We're looking for blends between FADD and FSUB nodes. We insist on these
22483   // nodes being lined up in a specific expected pattern.
22484   if (!(isShuffleEquivalent(Mask, 0, 3) ||
22485         isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
22486         isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
22487     return SDValue();
22488
22489   // Only specific types are legal at this point, assert so we notice if and
22490   // when these change.
22491   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22492           VT == MVT::v4f64) &&
22493          "Unknown vector type encountered!");
22494
22495   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22496 }
22497
22498 /// PerformShuffleCombine - Performs several different shuffle combines.
22499 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22500                                      TargetLowering::DAGCombinerInfo &DCI,
22501                                      const X86Subtarget *Subtarget) {
22502   SDLoc dl(N);
22503   SDValue N0 = N->getOperand(0);
22504   SDValue N1 = N->getOperand(1);
22505   EVT VT = N->getValueType(0);
22506
22507   // Don't create instructions with illegal types after legalize types has run.
22508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22509   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22510     return SDValue();
22511
22512   // If we have legalized the vector types, look for blends of FADD and FSUB
22513   // nodes that we can fuse into an ADDSUB node.
22514   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22515     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22516       return AddSub;
22517
22518   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22519   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22520       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22521     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22522
22523   // During Type Legalization, when promoting illegal vector types,
22524   // the backend might introduce new shuffle dag nodes and bitcasts.
22525   //
22526   // This code performs the following transformation:
22527   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22528   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22529   //
22530   // We do this only if both the bitcast and the BINOP dag nodes have
22531   // one use. Also, perform this transformation only if the new binary
22532   // operation is legal. This is to avoid introducing dag nodes that
22533   // potentially need to be further expanded (or custom lowered) into a
22534   // less optimal sequence of dag nodes.
22535   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22536       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22537       N0.getOpcode() == ISD::BITCAST) {
22538     SDValue BC0 = N0.getOperand(0);
22539     EVT SVT = BC0.getValueType();
22540     unsigned Opcode = BC0.getOpcode();
22541     unsigned NumElts = VT.getVectorNumElements();
22542
22543     if (BC0.hasOneUse() && SVT.isVector() &&
22544         SVT.getVectorNumElements() * 2 == NumElts &&
22545         TLI.isOperationLegal(Opcode, VT)) {
22546       bool CanFold = false;
22547       switch (Opcode) {
22548       default : break;
22549       case ISD::ADD :
22550       case ISD::FADD :
22551       case ISD::SUB :
22552       case ISD::FSUB :
22553       case ISD::MUL :
22554       case ISD::FMUL :
22555         CanFold = true;
22556       }
22557
22558       unsigned SVTNumElts = SVT.getVectorNumElements();
22559       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22560       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22561         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22562       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22563         CanFold = SVOp->getMaskElt(i) < 0;
22564
22565       if (CanFold) {
22566         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
22567         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
22568         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22569         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22570       }
22571     }
22572   }
22573
22574   // Only handle 128 wide vector from here on.
22575   if (!VT.is128BitVector())
22576     return SDValue();
22577
22578   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22579   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22580   // consecutive, non-overlapping, and in the right order.
22581   SmallVector<SDValue, 16> Elts;
22582   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22583     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22584
22585   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
22586   if (LD.getNode())
22587     return LD;
22588
22589   if (isTargetShuffle(N->getOpcode())) {
22590     SDValue Shuffle =
22591         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22592     if (Shuffle.getNode())
22593       return Shuffle;
22594
22595     // Try recursively combining arbitrary sequences of x86 shuffle
22596     // instructions into higher-order shuffles. We do this after combining
22597     // specific PSHUF instruction sequences into their minimal form so that we
22598     // can evaluate how many specialized shuffle instructions are involved in
22599     // a particular chain.
22600     SmallVector<int, 1> NonceMask; // Just a placeholder.
22601     NonceMask.push_back(0);
22602     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22603                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22604                                       DCI, Subtarget))
22605       return SDValue(); // This routine will use CombineTo to replace N.
22606   }
22607
22608   return SDValue();
22609 }
22610
22611 /// PerformTruncateCombine - Converts truncate operation to
22612 /// a sequence of vector shuffle operations.
22613 /// It is possible when we truncate 256-bit vector to 128-bit vector
22614 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
22615                                       TargetLowering::DAGCombinerInfo &DCI,
22616                                       const X86Subtarget *Subtarget)  {
22617   return SDValue();
22618 }
22619
22620 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22621 /// specific shuffle of a load can be folded into a single element load.
22622 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22623 /// shuffles have been custom lowered so we need to handle those here.
22624 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22625                                          TargetLowering::DAGCombinerInfo &DCI) {
22626   if (DCI.isBeforeLegalizeOps())
22627     return SDValue();
22628
22629   SDValue InVec = N->getOperand(0);
22630   SDValue EltNo = N->getOperand(1);
22631
22632   if (!isa<ConstantSDNode>(EltNo))
22633     return SDValue();
22634
22635   EVT OriginalVT = InVec.getValueType();
22636
22637   if (InVec.getOpcode() == ISD::BITCAST) {
22638     // Don't duplicate a load with other uses.
22639     if (!InVec.hasOneUse())
22640       return SDValue();
22641     EVT BCVT = InVec.getOperand(0).getValueType();
22642     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22643       return SDValue();
22644     InVec = InVec.getOperand(0);
22645   }
22646
22647   EVT CurrentVT = InVec.getValueType();
22648
22649   if (!isTargetShuffle(InVec.getOpcode()))
22650     return SDValue();
22651
22652   // Don't duplicate a load with other uses.
22653   if (!InVec.hasOneUse())
22654     return SDValue();
22655
22656   SmallVector<int, 16> ShuffleMask;
22657   bool UnaryShuffle;
22658   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22659                             ShuffleMask, UnaryShuffle))
22660     return SDValue();
22661
22662   // Select the input vector, guarding against out of range extract vector.
22663   unsigned NumElems = CurrentVT.getVectorNumElements();
22664   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22665   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22666   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22667                                          : InVec.getOperand(1);
22668
22669   // If inputs to shuffle are the same for both ops, then allow 2 uses
22670   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22671
22672   if (LdNode.getOpcode() == ISD::BITCAST) {
22673     // Don't duplicate a load with other uses.
22674     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22675       return SDValue();
22676
22677     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22678     LdNode = LdNode.getOperand(0);
22679   }
22680
22681   if (!ISD::isNormalLoad(LdNode.getNode()))
22682     return SDValue();
22683
22684   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22685
22686   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22687     return SDValue();
22688
22689   EVT EltVT = N->getValueType(0);
22690   // If there's a bitcast before the shuffle, check if the load type and
22691   // alignment is valid.
22692   unsigned Align = LN0->getAlignment();
22693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22694   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
22695       EltVT.getTypeForEVT(*DAG.getContext()));
22696
22697   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22698     return SDValue();
22699
22700   // All checks match so transform back to vector_shuffle so that DAG combiner
22701   // can finish the job
22702   SDLoc dl(N);
22703
22704   // Create shuffle node taking into account the case that its a unary shuffle
22705   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22706                                    : InVec.getOperand(1);
22707   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22708                                  InVec.getOperand(0), Shuffle,
22709                                  &ShuffleMask[0]);
22710   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
22711   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22712                      EltNo);
22713 }
22714
22715 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22716 /// generation and convert it from being a bunch of shuffles and extracts
22717 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22718 /// storing the value and loading scalars back, while for x64 we should
22719 /// use 64-bit extracts and shifts.
22720 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22721                                          TargetLowering::DAGCombinerInfo &DCI) {
22722   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
22723   if (NewOp.getNode())
22724     return NewOp;
22725
22726   SDValue InputVector = N->getOperand(0);
22727
22728   // Detect whether we are trying to convert from mmx to i32 and the bitcast
22729   // from mmx to v2i32 has a single usage.
22730   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
22731       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
22732       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
22733     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22734                        N->getValueType(0),
22735                        InputVector.getNode()->getOperand(0));
22736
22737   // Only operate on vectors of 4 elements, where the alternative shuffling
22738   // gets to be more expensive.
22739   if (InputVector.getValueType() != MVT::v4i32)
22740     return SDValue();
22741
22742   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22743   // single use which is a sign-extend or zero-extend, and all elements are
22744   // used.
22745   SmallVector<SDNode *, 4> Uses;
22746   unsigned ExtractedElements = 0;
22747   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22748        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22749     if (UI.getUse().getResNo() != InputVector.getResNo())
22750       return SDValue();
22751
22752     SDNode *Extract = *UI;
22753     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22754       return SDValue();
22755
22756     if (Extract->getValueType(0) != MVT::i32)
22757       return SDValue();
22758     if (!Extract->hasOneUse())
22759       return SDValue();
22760     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22761         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22762       return SDValue();
22763     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22764       return SDValue();
22765
22766     // Record which element was extracted.
22767     ExtractedElements |=
22768       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22769
22770     Uses.push_back(Extract);
22771   }
22772
22773   // If not all the elements were used, this may not be worthwhile.
22774   if (ExtractedElements != 15)
22775     return SDValue();
22776
22777   // Ok, we've now decided to do the transformation.
22778   // If 64-bit shifts are legal, use the extract-shift sequence,
22779   // otherwise bounce the vector off the cache.
22780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22781   SDValue Vals[4];
22782   SDLoc dl(InputVector);
22783
22784   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22785     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
22786     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
22787     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22788       DAG.getConstant(0, VecIdxTy));
22789     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22790       DAG.getConstant(1, VecIdxTy));
22791
22792     SDValue ShAmt = DAG.getConstant(32,
22793       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
22794     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22795     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22796       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22797     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22798     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22799       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22800   } else {
22801     // Store the value to a temporary stack slot.
22802     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22803     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22804       MachinePointerInfo(), false, false, 0);
22805
22806     EVT ElementType = InputVector.getValueType().getVectorElementType();
22807     unsigned EltSize = ElementType.getSizeInBits() / 8;
22808
22809     // Replace each use (extract) with a load of the appropriate element.
22810     for (unsigned i = 0; i < 4; ++i) {
22811       uint64_t Offset = EltSize * i;
22812       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
22813
22814       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
22815                                        StackPtr, OffsetVal);
22816
22817       // Load the scalar.
22818       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22819                             ScalarAddr, MachinePointerInfo(),
22820                             false, false, false, 0);
22821
22822     }
22823   }
22824
22825   // Replace the extracts
22826   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22827     UE = Uses.end(); UI != UE; ++UI) {
22828     SDNode *Extract = *UI;
22829
22830     SDValue Idx = Extract->getOperand(1);
22831     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22832     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22833   }
22834
22835   // The replacement was made in place; don't return anything.
22836   return SDValue();
22837 }
22838
22839 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22840 static std::pair<unsigned, bool>
22841 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22842                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22843   if (!VT.isVector())
22844     return std::make_pair(0, false);
22845
22846   bool NeedSplit = false;
22847   switch (VT.getSimpleVT().SimpleTy) {
22848   default: return std::make_pair(0, false);
22849   case MVT::v4i64:
22850   case MVT::v2i64:
22851     if (!Subtarget->hasVLX())
22852       return std::make_pair(0, false);
22853     break;
22854   case MVT::v64i8:
22855   case MVT::v32i16:
22856     if (!Subtarget->hasBWI())
22857       return std::make_pair(0, false);
22858     break;
22859   case MVT::v16i32:
22860   case MVT::v8i64:
22861     if (!Subtarget->hasAVX512())
22862       return std::make_pair(0, false);
22863     break;
22864   case MVT::v32i8:
22865   case MVT::v16i16:
22866   case MVT::v8i32:
22867     if (!Subtarget->hasAVX2())
22868       NeedSplit = true;
22869     if (!Subtarget->hasAVX())
22870       return std::make_pair(0, false);
22871     break;
22872   case MVT::v16i8:
22873   case MVT::v8i16:
22874   case MVT::v4i32:
22875     if (!Subtarget->hasSSE2())
22876       return std::make_pair(0, false);
22877   }
22878
22879   // SSE2 has only a small subset of the operations.
22880   bool hasUnsigned = Subtarget->hasSSE41() ||
22881                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22882   bool hasSigned = Subtarget->hasSSE41() ||
22883                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22884
22885   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22886
22887   unsigned Opc = 0;
22888   // Check for x CC y ? x : y.
22889   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22890       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22891     switch (CC) {
22892     default: break;
22893     case ISD::SETULT:
22894     case ISD::SETULE:
22895       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22896     case ISD::SETUGT:
22897     case ISD::SETUGE:
22898       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22899     case ISD::SETLT:
22900     case ISD::SETLE:
22901       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22902     case ISD::SETGT:
22903     case ISD::SETGE:
22904       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22905     }
22906   // Check for x CC y ? y : x -- a min/max with reversed arms.
22907   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22908              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22909     switch (CC) {
22910     default: break;
22911     case ISD::SETULT:
22912     case ISD::SETULE:
22913       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22914     case ISD::SETUGT:
22915     case ISD::SETUGE:
22916       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22917     case ISD::SETLT:
22918     case ISD::SETLE:
22919       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22920     case ISD::SETGT:
22921     case ISD::SETGE:
22922       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22923     }
22924   }
22925
22926   return std::make_pair(Opc, NeedSplit);
22927 }
22928
22929 static SDValue
22930 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22931                                       const X86Subtarget *Subtarget) {
22932   SDLoc dl(N);
22933   SDValue Cond = N->getOperand(0);
22934   SDValue LHS = N->getOperand(1);
22935   SDValue RHS = N->getOperand(2);
22936
22937   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22938     SDValue CondSrc = Cond->getOperand(0);
22939     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22940       Cond = CondSrc->getOperand(0);
22941   }
22942
22943   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22944     return SDValue();
22945
22946   // A vselect where all conditions and data are constants can be optimized into
22947   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22948   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22949       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22950     return SDValue();
22951
22952   unsigned MaskValue = 0;
22953   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22954     return SDValue();
22955
22956   MVT VT = N->getSimpleValueType(0);
22957   unsigned NumElems = VT.getVectorNumElements();
22958   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22959   for (unsigned i = 0; i < NumElems; ++i) {
22960     // Be sure we emit undef where we can.
22961     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22962       ShuffleMask[i] = -1;
22963     else
22964       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22965   }
22966
22967   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22968   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22969     return SDValue();
22970   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22971 }
22972
22973 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22974 /// nodes.
22975 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22976                                     TargetLowering::DAGCombinerInfo &DCI,
22977                                     const X86Subtarget *Subtarget) {
22978   SDLoc DL(N);
22979   SDValue Cond = N->getOperand(0);
22980   // Get the LHS/RHS of the select.
22981   SDValue LHS = N->getOperand(1);
22982   SDValue RHS = N->getOperand(2);
22983   EVT VT = LHS.getValueType();
22984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22985
22986   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22987   // instructions match the semantics of the common C idiom x<y?x:y but not
22988   // x<=y?x:y, because of how they handle negative zero (which can be
22989   // ignored in unsafe-math mode).
22990   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22991       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
22992       (Subtarget->hasSSE2() ||
22993        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22994     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22995
22996     unsigned Opcode = 0;
22997     // Check for x CC y ? x : y.
22998     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22999         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23000       switch (CC) {
23001       default: break;
23002       case ISD::SETULT:
23003         // Converting this to a min would handle NaNs incorrectly, and swapping
23004         // the operands would cause it to handle comparisons between positive
23005         // and negative zero incorrectly.
23006         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23007           if (!DAG.getTarget().Options.UnsafeFPMath &&
23008               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23009             break;
23010           std::swap(LHS, RHS);
23011         }
23012         Opcode = X86ISD::FMIN;
23013         break;
23014       case ISD::SETOLE:
23015         // Converting this to a min would handle comparisons between positive
23016         // and negative zero incorrectly.
23017         if (!DAG.getTarget().Options.UnsafeFPMath &&
23018             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23019           break;
23020         Opcode = X86ISD::FMIN;
23021         break;
23022       case ISD::SETULE:
23023         // Converting this to a min would handle both negative zeros and NaNs
23024         // incorrectly, but we can swap the operands to fix both.
23025         std::swap(LHS, RHS);
23026       case ISD::SETOLT:
23027       case ISD::SETLT:
23028       case ISD::SETLE:
23029         Opcode = X86ISD::FMIN;
23030         break;
23031
23032       case ISD::SETOGE:
23033         // Converting this to a max would handle comparisons between positive
23034         // and negative zero incorrectly.
23035         if (!DAG.getTarget().Options.UnsafeFPMath &&
23036             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23037           break;
23038         Opcode = X86ISD::FMAX;
23039         break;
23040       case ISD::SETUGT:
23041         // Converting this to a max would handle NaNs incorrectly, and swapping
23042         // the operands would cause it to handle comparisons between positive
23043         // and negative zero incorrectly.
23044         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23045           if (!DAG.getTarget().Options.UnsafeFPMath &&
23046               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23047             break;
23048           std::swap(LHS, RHS);
23049         }
23050         Opcode = X86ISD::FMAX;
23051         break;
23052       case ISD::SETUGE:
23053         // Converting this to a max would handle both negative zeros and NaNs
23054         // incorrectly, but we can swap the operands to fix both.
23055         std::swap(LHS, RHS);
23056       case ISD::SETOGT:
23057       case ISD::SETGT:
23058       case ISD::SETGE:
23059         Opcode = X86ISD::FMAX;
23060         break;
23061       }
23062     // Check for x CC y ? y : x -- a min/max with reversed arms.
23063     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23064                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23065       switch (CC) {
23066       default: break;
23067       case ISD::SETOGE:
23068         // Converting this to a min would handle comparisons between positive
23069         // and negative zero incorrectly, and swapping the operands would
23070         // cause it to handle NaNs incorrectly.
23071         if (!DAG.getTarget().Options.UnsafeFPMath &&
23072             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23073           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23074             break;
23075           std::swap(LHS, RHS);
23076         }
23077         Opcode = X86ISD::FMIN;
23078         break;
23079       case ISD::SETUGT:
23080         // Converting this to a min would handle NaNs incorrectly.
23081         if (!DAG.getTarget().Options.UnsafeFPMath &&
23082             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23083           break;
23084         Opcode = X86ISD::FMIN;
23085         break;
23086       case ISD::SETUGE:
23087         // Converting this to a min would handle both negative zeros and NaNs
23088         // incorrectly, but we can swap the operands to fix both.
23089         std::swap(LHS, RHS);
23090       case ISD::SETOGT:
23091       case ISD::SETGT:
23092       case ISD::SETGE:
23093         Opcode = X86ISD::FMIN;
23094         break;
23095
23096       case ISD::SETULT:
23097         // Converting this to a max would handle NaNs incorrectly.
23098         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23099           break;
23100         Opcode = X86ISD::FMAX;
23101         break;
23102       case ISD::SETOLE:
23103         // Converting this to a max would handle comparisons between positive
23104         // and negative zero incorrectly, and swapping the operands would
23105         // cause it to handle NaNs incorrectly.
23106         if (!DAG.getTarget().Options.UnsafeFPMath &&
23107             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23108           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23109             break;
23110           std::swap(LHS, RHS);
23111         }
23112         Opcode = X86ISD::FMAX;
23113         break;
23114       case ISD::SETULE:
23115         // Converting this to a max would handle both negative zeros and NaNs
23116         // incorrectly, but we can swap the operands to fix both.
23117         std::swap(LHS, RHS);
23118       case ISD::SETOLT:
23119       case ISD::SETLT:
23120       case ISD::SETLE:
23121         Opcode = X86ISD::FMAX;
23122         break;
23123       }
23124     }
23125
23126     if (Opcode)
23127       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23128   }
23129
23130   EVT CondVT = Cond.getValueType();
23131   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23132       CondVT.getVectorElementType() == MVT::i1) {
23133     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23134     // lowering on KNL. In this case we convert it to
23135     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23136     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23137     // Since SKX these selects have a proper lowering.
23138     EVT OpVT = LHS.getValueType();
23139     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23140         (OpVT.getVectorElementType() == MVT::i8 ||
23141          OpVT.getVectorElementType() == MVT::i16) &&
23142         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23143       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23144       DCI.AddToWorklist(Cond.getNode());
23145       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23146     }
23147   }
23148   // If this is a select between two integer constants, try to do some
23149   // optimizations.
23150   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23151     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23152       // Don't do this for crazy integer types.
23153       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23154         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23155         // so that TrueC (the true value) is larger than FalseC.
23156         bool NeedsCondInvert = false;
23157
23158         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23159             // Efficiently invertible.
23160             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23161              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23162               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23163           NeedsCondInvert = true;
23164           std::swap(TrueC, FalseC);
23165         }
23166
23167         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23168         if (FalseC->getAPIntValue() == 0 &&
23169             TrueC->getAPIntValue().isPowerOf2()) {
23170           if (NeedsCondInvert) // Invert the condition if needed.
23171             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23172                                DAG.getConstant(1, Cond.getValueType()));
23173
23174           // Zero extend the condition if needed.
23175           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23176
23177           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23178           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23179                              DAG.getConstant(ShAmt, MVT::i8));
23180         }
23181
23182         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23183         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23184           if (NeedsCondInvert) // Invert the condition if needed.
23185             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23186                                DAG.getConstant(1, Cond.getValueType()));
23187
23188           // Zero extend the condition if needed.
23189           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23190                              FalseC->getValueType(0), Cond);
23191           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23192                              SDValue(FalseC, 0));
23193         }
23194
23195         // Optimize cases that will turn into an LEA instruction.  This requires
23196         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23197         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23198           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23199           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23200
23201           bool isFastMultiplier = false;
23202           if (Diff < 10) {
23203             switch ((unsigned char)Diff) {
23204               default: break;
23205               case 1:  // result = add base, cond
23206               case 2:  // result = lea base(    , cond*2)
23207               case 3:  // result = lea base(cond, cond*2)
23208               case 4:  // result = lea base(    , cond*4)
23209               case 5:  // result = lea base(cond, cond*4)
23210               case 8:  // result = lea base(    , cond*8)
23211               case 9:  // result = lea base(cond, cond*8)
23212                 isFastMultiplier = true;
23213                 break;
23214             }
23215           }
23216
23217           if (isFastMultiplier) {
23218             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23219             if (NeedsCondInvert) // Invert the condition if needed.
23220               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23221                                  DAG.getConstant(1, Cond.getValueType()));
23222
23223             // Zero extend the condition if needed.
23224             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23225                                Cond);
23226             // Scale the condition by the difference.
23227             if (Diff != 1)
23228               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23229                                  DAG.getConstant(Diff, Cond.getValueType()));
23230
23231             // Add the base if non-zero.
23232             if (FalseC->getAPIntValue() != 0)
23233               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23234                                  SDValue(FalseC, 0));
23235             return Cond;
23236           }
23237         }
23238       }
23239   }
23240
23241   // Canonicalize max and min:
23242   // (x > y) ? x : y -> (x >= y) ? x : y
23243   // (x < y) ? x : y -> (x <= y) ? x : y
23244   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23245   // the need for an extra compare
23246   // against zero. e.g.
23247   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23248   // subl   %esi, %edi
23249   // testl  %edi, %edi
23250   // movl   $0, %eax
23251   // cmovgl %edi, %eax
23252   // =>
23253   // xorl   %eax, %eax
23254   // subl   %esi, $edi
23255   // cmovsl %eax, %edi
23256   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23257       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23258       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23259     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23260     switch (CC) {
23261     default: break;
23262     case ISD::SETLT:
23263     case ISD::SETGT: {
23264       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23265       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23266                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23267       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23268     }
23269     }
23270   }
23271
23272   // Early exit check
23273   if (!TLI.isTypeLegal(VT))
23274     return SDValue();
23275
23276   // Match VSELECTs into subs with unsigned saturation.
23277   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23278       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23279       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23280        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23281     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23282
23283     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23284     // left side invert the predicate to simplify logic below.
23285     SDValue Other;
23286     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23287       Other = RHS;
23288       CC = ISD::getSetCCInverse(CC, true);
23289     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23290       Other = LHS;
23291     }
23292
23293     if (Other.getNode() && Other->getNumOperands() == 2 &&
23294         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23295       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23296       SDValue CondRHS = Cond->getOperand(1);
23297
23298       // Look for a general sub with unsigned saturation first.
23299       // x >= y ? x-y : 0 --> subus x, y
23300       // x >  y ? x-y : 0 --> subus x, y
23301       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23302           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23303         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23304
23305       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23306         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23307           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23308             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23309               // If the RHS is a constant we have to reverse the const
23310               // canonicalization.
23311               // x > C-1 ? x+-C : 0 --> subus x, C
23312               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23313                   CondRHSConst->getAPIntValue() ==
23314                       (-OpRHSConst->getAPIntValue() - 1))
23315                 return DAG.getNode(
23316                     X86ISD::SUBUS, DL, VT, OpLHS,
23317                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
23318
23319           // Another special case: If C was a sign bit, the sub has been
23320           // canonicalized into a xor.
23321           // FIXME: Would it be better to use computeKnownBits to determine
23322           //        whether it's safe to decanonicalize the xor?
23323           // x s< 0 ? x^C : 0 --> subus x, C
23324           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23325               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23326               OpRHSConst->getAPIntValue().isSignBit())
23327             // Note that we have to rebuild the RHS constant here to ensure we
23328             // don't rely on particular values of undef lanes.
23329             return DAG.getNode(
23330                 X86ISD::SUBUS, DL, VT, OpLHS,
23331                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
23332         }
23333     }
23334   }
23335
23336   // Try to match a min/max vector operation.
23337   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
23338     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
23339     unsigned Opc = ret.first;
23340     bool NeedSplit = ret.second;
23341
23342     if (Opc && NeedSplit) {
23343       unsigned NumElems = VT.getVectorNumElements();
23344       // Extract the LHS vectors
23345       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
23346       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
23347
23348       // Extract the RHS vectors
23349       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
23350       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
23351
23352       // Create min/max for each subvector
23353       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
23354       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
23355
23356       // Merge the result
23357       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
23358     } else if (Opc)
23359       return DAG.getNode(Opc, DL, VT, LHS, RHS);
23360   }
23361
23362   // Simplify vector selection if condition value type matches vselect
23363   // operand type
23364   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23365     assert(Cond.getValueType().isVector() &&
23366            "vector select expects a vector selector!");
23367
23368     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23369     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23370
23371     // Try invert the condition if true value is not all 1s and false value
23372     // is not all 0s.
23373     if (!TValIsAllOnes && !FValIsAllZeros &&
23374         // Check if the selector will be produced by CMPP*/PCMP*
23375         Cond.getOpcode() == ISD::SETCC &&
23376         // Check if SETCC has already been promoted
23377         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
23378       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23379       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23380
23381       if (TValIsAllZeros || FValIsAllOnes) {
23382         SDValue CC = Cond.getOperand(2);
23383         ISD::CondCode NewCC =
23384           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23385                                Cond.getOperand(0).getValueType().isInteger());
23386         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23387         std::swap(LHS, RHS);
23388         TValIsAllOnes = FValIsAllOnes;
23389         FValIsAllZeros = TValIsAllZeros;
23390       }
23391     }
23392
23393     if (TValIsAllOnes || FValIsAllZeros) {
23394       SDValue Ret;
23395
23396       if (TValIsAllOnes && FValIsAllZeros)
23397         Ret = Cond;
23398       else if (TValIsAllOnes)
23399         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
23400                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
23401       else if (FValIsAllZeros)
23402         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23403                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
23404
23405       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
23406     }
23407   }
23408
23409   // If we know that this node is legal then we know that it is going to be
23410   // matched by one of the SSE/AVX BLEND instructions. These instructions only
23411   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
23412   // to simplify previous instructions.
23413   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23414       !DCI.isBeforeLegalize() &&
23415       // We explicitly check against v8i16 and v16i16 because, although
23416       // they're marked as Custom, they might only be legal when Cond is a
23417       // build_vector of constants. This will be taken care in a later
23418       // condition.
23419       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
23420        VT != MVT::v8i16) &&
23421       // Don't optimize vector of constants. Those are handled by
23422       // the generic code and all the bits must be properly set for
23423       // the generic optimizer.
23424       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23425     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23426
23427     // Don't optimize vector selects that map to mask-registers.
23428     if (BitWidth == 1)
23429       return SDValue();
23430
23431     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23432     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23433
23434     APInt KnownZero, KnownOne;
23435     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23436                                           DCI.isBeforeLegalizeOps());
23437     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23438         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23439                                  TLO)) {
23440       // If we changed the computation somewhere in the DAG, this change
23441       // will affect all users of Cond.
23442       // Make sure it is fine and update all the nodes so that we do not
23443       // use the generic VSELECT anymore. Otherwise, we may perform
23444       // wrong optimizations as we messed up with the actual expectation
23445       // for the vector boolean values.
23446       if (Cond != TLO.Old) {
23447         // Check all uses of that condition operand to check whether it will be
23448         // consumed by non-BLEND instructions, which may depend on all bits are
23449         // set properly.
23450         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23451              I != E; ++I)
23452           if (I->getOpcode() != ISD::VSELECT)
23453             // TODO: Add other opcodes eventually lowered into BLEND.
23454             return SDValue();
23455
23456         // Update all the users of the condition, before committing the change,
23457         // so that the VSELECT optimizations that expect the correct vector
23458         // boolean value will not be triggered.
23459         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23460              I != E; ++I)
23461           DAG.ReplaceAllUsesOfValueWith(
23462               SDValue(*I, 0),
23463               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23464                           Cond, I->getOperand(1), I->getOperand(2)));
23465         DCI.CommitTargetLoweringOpt(TLO);
23466         return SDValue();
23467       }
23468       // At this point, only Cond is changed. Change the condition
23469       // just for N to keep the opportunity to optimize all other
23470       // users their own way.
23471       DAG.ReplaceAllUsesOfValueWith(
23472           SDValue(N, 0),
23473           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23474                       TLO.New, N->getOperand(1), N->getOperand(2)));
23475       return SDValue();
23476     }
23477   }
23478
23479   // We should generate an X86ISD::BLENDI from a vselect if its argument
23480   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23481   // constants. This specific pattern gets generated when we split a
23482   // selector for a 512 bit vector in a machine without AVX512 (but with
23483   // 256-bit vectors), during legalization:
23484   //
23485   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23486   //
23487   // Iff we find this pattern and the build_vectors are built from
23488   // constants, we translate the vselect into a shuffle_vector that we
23489   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23490   if ((N->getOpcode() == ISD::VSELECT ||
23491        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23492       !DCI.isBeforeLegalize()) {
23493     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23494     if (Shuffle.getNode())
23495       return Shuffle;
23496   }
23497
23498   return SDValue();
23499 }
23500
23501 // Check whether a boolean test is testing a boolean value generated by
23502 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23503 // code.
23504 //
23505 // Simplify the following patterns:
23506 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23507 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23508 // to (Op EFLAGS Cond)
23509 //
23510 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23511 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23512 // to (Op EFLAGS !Cond)
23513 //
23514 // where Op could be BRCOND or CMOV.
23515 //
23516 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23517   // Quit if not CMP and SUB with its value result used.
23518   if (Cmp.getOpcode() != X86ISD::CMP &&
23519       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23520       return SDValue();
23521
23522   // Quit if not used as a boolean value.
23523   if (CC != X86::COND_E && CC != X86::COND_NE)
23524     return SDValue();
23525
23526   // Check CMP operands. One of them should be 0 or 1 and the other should be
23527   // an SetCC or extended from it.
23528   SDValue Op1 = Cmp.getOperand(0);
23529   SDValue Op2 = Cmp.getOperand(1);
23530
23531   SDValue SetCC;
23532   const ConstantSDNode* C = nullptr;
23533   bool needOppositeCond = (CC == X86::COND_E);
23534   bool checkAgainstTrue = false; // Is it a comparison against 1?
23535
23536   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23537     SetCC = Op2;
23538   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23539     SetCC = Op1;
23540   else // Quit if all operands are not constants.
23541     return SDValue();
23542
23543   if (C->getZExtValue() == 1) {
23544     needOppositeCond = !needOppositeCond;
23545     checkAgainstTrue = true;
23546   } else if (C->getZExtValue() != 0)
23547     // Quit if the constant is neither 0 or 1.
23548     return SDValue();
23549
23550   bool truncatedToBoolWithAnd = false;
23551   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23552   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23553          SetCC.getOpcode() == ISD::TRUNCATE ||
23554          SetCC.getOpcode() == ISD::AND) {
23555     if (SetCC.getOpcode() == ISD::AND) {
23556       int OpIdx = -1;
23557       ConstantSDNode *CS;
23558       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23559           CS->getZExtValue() == 1)
23560         OpIdx = 1;
23561       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23562           CS->getZExtValue() == 1)
23563         OpIdx = 0;
23564       if (OpIdx == -1)
23565         break;
23566       SetCC = SetCC.getOperand(OpIdx);
23567       truncatedToBoolWithAnd = true;
23568     } else
23569       SetCC = SetCC.getOperand(0);
23570   }
23571
23572   switch (SetCC.getOpcode()) {
23573   case X86ISD::SETCC_CARRY:
23574     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23575     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23576     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23577     // truncated to i1 using 'and'.
23578     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23579       break;
23580     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23581            "Invalid use of SETCC_CARRY!");
23582     // FALL THROUGH
23583   case X86ISD::SETCC:
23584     // Set the condition code or opposite one if necessary.
23585     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23586     if (needOppositeCond)
23587       CC = X86::GetOppositeBranchCondition(CC);
23588     return SetCC.getOperand(1);
23589   case X86ISD::CMOV: {
23590     // Check whether false/true value has canonical one, i.e. 0 or 1.
23591     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23592     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23593     // Quit if true value is not a constant.
23594     if (!TVal)
23595       return SDValue();
23596     // Quit if false value is not a constant.
23597     if (!FVal) {
23598       SDValue Op = SetCC.getOperand(0);
23599       // Skip 'zext' or 'trunc' node.
23600       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23601           Op.getOpcode() == ISD::TRUNCATE)
23602         Op = Op.getOperand(0);
23603       // A special case for rdrand/rdseed, where 0 is set if false cond is
23604       // found.
23605       if ((Op.getOpcode() != X86ISD::RDRAND &&
23606            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23607         return SDValue();
23608     }
23609     // Quit if false value is not the constant 0 or 1.
23610     bool FValIsFalse = true;
23611     if (FVal && FVal->getZExtValue() != 0) {
23612       if (FVal->getZExtValue() != 1)
23613         return SDValue();
23614       // If FVal is 1, opposite cond is needed.
23615       needOppositeCond = !needOppositeCond;
23616       FValIsFalse = false;
23617     }
23618     // Quit if TVal is not the constant opposite of FVal.
23619     if (FValIsFalse && TVal->getZExtValue() != 1)
23620       return SDValue();
23621     if (!FValIsFalse && TVal->getZExtValue() != 0)
23622       return SDValue();
23623     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23624     if (needOppositeCond)
23625       CC = X86::GetOppositeBranchCondition(CC);
23626     return SetCC.getOperand(3);
23627   }
23628   }
23629
23630   return SDValue();
23631 }
23632
23633 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23634 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23635                                   TargetLowering::DAGCombinerInfo &DCI,
23636                                   const X86Subtarget *Subtarget) {
23637   SDLoc DL(N);
23638
23639   // If the flag operand isn't dead, don't touch this CMOV.
23640   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23641     return SDValue();
23642
23643   SDValue FalseOp = N->getOperand(0);
23644   SDValue TrueOp = N->getOperand(1);
23645   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23646   SDValue Cond = N->getOperand(3);
23647
23648   if (CC == X86::COND_E || CC == X86::COND_NE) {
23649     switch (Cond.getOpcode()) {
23650     default: break;
23651     case X86ISD::BSR:
23652     case X86ISD::BSF:
23653       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23654       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23655         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23656     }
23657   }
23658
23659   SDValue Flags;
23660
23661   Flags = checkBoolTestSetCCCombine(Cond, CC);
23662   if (Flags.getNode() &&
23663       // Extra check as FCMOV only supports a subset of X86 cond.
23664       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23665     SDValue Ops[] = { FalseOp, TrueOp,
23666                       DAG.getConstant(CC, MVT::i8), Flags };
23667     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23668   }
23669
23670   // If this is a select between two integer constants, try to do some
23671   // optimizations.  Note that the operands are ordered the opposite of SELECT
23672   // operands.
23673   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23674     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23675       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23676       // larger than FalseC (the false value).
23677       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23678         CC = X86::GetOppositeBranchCondition(CC);
23679         std::swap(TrueC, FalseC);
23680         std::swap(TrueOp, FalseOp);
23681       }
23682
23683       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23684       // This is efficient for any integer data type (including i8/i16) and
23685       // shift amount.
23686       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23687         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23688                            DAG.getConstant(CC, MVT::i8), Cond);
23689
23690         // Zero extend the condition if needed.
23691         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23692
23693         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23694         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23695                            DAG.getConstant(ShAmt, MVT::i8));
23696         if (N->getNumValues() == 2)  // Dead flag value?
23697           return DCI.CombineTo(N, Cond, SDValue());
23698         return Cond;
23699       }
23700
23701       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23702       // for any integer data type, including i8/i16.
23703       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23704         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23705                            DAG.getConstant(CC, MVT::i8), Cond);
23706
23707         // Zero extend the condition if needed.
23708         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23709                            FalseC->getValueType(0), Cond);
23710         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23711                            SDValue(FalseC, 0));
23712
23713         if (N->getNumValues() == 2)  // Dead flag value?
23714           return DCI.CombineTo(N, Cond, SDValue());
23715         return Cond;
23716       }
23717
23718       // Optimize cases that will turn into an LEA instruction.  This requires
23719       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23720       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23721         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23722         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23723
23724         bool isFastMultiplier = false;
23725         if (Diff < 10) {
23726           switch ((unsigned char)Diff) {
23727           default: break;
23728           case 1:  // result = add base, cond
23729           case 2:  // result = lea base(    , cond*2)
23730           case 3:  // result = lea base(cond, cond*2)
23731           case 4:  // result = lea base(    , cond*4)
23732           case 5:  // result = lea base(cond, cond*4)
23733           case 8:  // result = lea base(    , cond*8)
23734           case 9:  // result = lea base(cond, cond*8)
23735             isFastMultiplier = true;
23736             break;
23737           }
23738         }
23739
23740         if (isFastMultiplier) {
23741           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23742           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23743                              DAG.getConstant(CC, MVT::i8), Cond);
23744           // Zero extend the condition if needed.
23745           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23746                              Cond);
23747           // Scale the condition by the difference.
23748           if (Diff != 1)
23749             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23750                                DAG.getConstant(Diff, Cond.getValueType()));
23751
23752           // Add the base if non-zero.
23753           if (FalseC->getAPIntValue() != 0)
23754             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23755                                SDValue(FalseC, 0));
23756           if (N->getNumValues() == 2)  // Dead flag value?
23757             return DCI.CombineTo(N, Cond, SDValue());
23758           return Cond;
23759         }
23760       }
23761     }
23762   }
23763
23764   // Handle these cases:
23765   //   (select (x != c), e, c) -> select (x != c), e, x),
23766   //   (select (x == c), c, e) -> select (x == c), x, e)
23767   // where the c is an integer constant, and the "select" is the combination
23768   // of CMOV and CMP.
23769   //
23770   // The rationale for this change is that the conditional-move from a constant
23771   // needs two instructions, however, conditional-move from a register needs
23772   // only one instruction.
23773   //
23774   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23775   //  some instruction-combining opportunities. This opt needs to be
23776   //  postponed as late as possible.
23777   //
23778   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23779     // the DCI.xxxx conditions are provided to postpone the optimization as
23780     // late as possible.
23781
23782     ConstantSDNode *CmpAgainst = nullptr;
23783     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23784         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23785         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23786
23787       if (CC == X86::COND_NE &&
23788           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23789         CC = X86::GetOppositeBranchCondition(CC);
23790         std::swap(TrueOp, FalseOp);
23791       }
23792
23793       if (CC == X86::COND_E &&
23794           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23795         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23796                           DAG.getConstant(CC, MVT::i8), Cond };
23797         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23798       }
23799     }
23800   }
23801
23802   return SDValue();
23803 }
23804
23805 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23806                                                 const X86Subtarget *Subtarget) {
23807   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23808   switch (IntNo) {
23809   default: return SDValue();
23810   // SSE/AVX/AVX2 blend intrinsics.
23811   case Intrinsic::x86_avx2_pblendvb:
23812   case Intrinsic::x86_avx2_pblendw:
23813   case Intrinsic::x86_avx2_pblendd_128:
23814   case Intrinsic::x86_avx2_pblendd_256:
23815     // Don't try to simplify this intrinsic if we don't have AVX2.
23816     if (!Subtarget->hasAVX2())
23817       return SDValue();
23818     // FALL-THROUGH
23819   case Intrinsic::x86_avx_blend_pd_256:
23820   case Intrinsic::x86_avx_blend_ps_256:
23821   case Intrinsic::x86_avx_blendv_pd_256:
23822   case Intrinsic::x86_avx_blendv_ps_256:
23823     // Don't try to simplify this intrinsic if we don't have AVX.
23824     if (!Subtarget->hasAVX())
23825       return SDValue();
23826     // FALL-THROUGH
23827   case Intrinsic::x86_sse41_pblendw:
23828   case Intrinsic::x86_sse41_blendpd:
23829   case Intrinsic::x86_sse41_blendps:
23830   case Intrinsic::x86_sse41_blendvps:
23831   case Intrinsic::x86_sse41_blendvpd:
23832   case Intrinsic::x86_sse41_pblendvb: {
23833     SDValue Op0 = N->getOperand(1);
23834     SDValue Op1 = N->getOperand(2);
23835     SDValue Mask = N->getOperand(3);
23836
23837     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23838     if (!Subtarget->hasSSE41())
23839       return SDValue();
23840
23841     // fold (blend A, A, Mask) -> A
23842     if (Op0 == Op1)
23843       return Op0;
23844     // fold (blend A, B, allZeros) -> A
23845     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23846       return Op0;
23847     // fold (blend A, B, allOnes) -> B
23848     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23849       return Op1;
23850
23851     // Simplify the case where the mask is a constant i32 value.
23852     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23853       if (C->isNullValue())
23854         return Op0;
23855       if (C->isAllOnesValue())
23856         return Op1;
23857     }
23858
23859     return SDValue();
23860   }
23861
23862   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23863   case Intrinsic::x86_sse2_psrai_w:
23864   case Intrinsic::x86_sse2_psrai_d:
23865   case Intrinsic::x86_avx2_psrai_w:
23866   case Intrinsic::x86_avx2_psrai_d:
23867   case Intrinsic::x86_sse2_psra_w:
23868   case Intrinsic::x86_sse2_psra_d:
23869   case Intrinsic::x86_avx2_psra_w:
23870   case Intrinsic::x86_avx2_psra_d: {
23871     SDValue Op0 = N->getOperand(1);
23872     SDValue Op1 = N->getOperand(2);
23873     EVT VT = Op0.getValueType();
23874     assert(VT.isVector() && "Expected a vector type!");
23875
23876     if (isa<BuildVectorSDNode>(Op1))
23877       Op1 = Op1.getOperand(0);
23878
23879     if (!isa<ConstantSDNode>(Op1))
23880       return SDValue();
23881
23882     EVT SVT = VT.getVectorElementType();
23883     unsigned SVTBits = SVT.getSizeInBits();
23884
23885     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23886     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23887     uint64_t ShAmt = C.getZExtValue();
23888
23889     // Don't try to convert this shift into a ISD::SRA if the shift
23890     // count is bigger than or equal to the element size.
23891     if (ShAmt >= SVTBits)
23892       return SDValue();
23893
23894     // Trivial case: if the shift count is zero, then fold this
23895     // into the first operand.
23896     if (ShAmt == 0)
23897       return Op0;
23898
23899     // Replace this packed shift intrinsic with a target independent
23900     // shift dag node.
23901     SDValue Splat = DAG.getConstant(C, VT);
23902     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
23903   }
23904   }
23905 }
23906
23907 /// PerformMulCombine - Optimize a single multiply with constant into two
23908 /// in order to implement it with two cheaper instructions, e.g.
23909 /// LEA + SHL, LEA + LEA.
23910 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23911                                  TargetLowering::DAGCombinerInfo &DCI) {
23912   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23913     return SDValue();
23914
23915   EVT VT = N->getValueType(0);
23916   if (VT != MVT::i64)
23917     return SDValue();
23918
23919   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23920   if (!C)
23921     return SDValue();
23922   uint64_t MulAmt = C->getZExtValue();
23923   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23924     return SDValue();
23925
23926   uint64_t MulAmt1 = 0;
23927   uint64_t MulAmt2 = 0;
23928   if ((MulAmt % 9) == 0) {
23929     MulAmt1 = 9;
23930     MulAmt2 = MulAmt / 9;
23931   } else if ((MulAmt % 5) == 0) {
23932     MulAmt1 = 5;
23933     MulAmt2 = MulAmt / 5;
23934   } else if ((MulAmt % 3) == 0) {
23935     MulAmt1 = 3;
23936     MulAmt2 = MulAmt / 3;
23937   }
23938   if (MulAmt2 &&
23939       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23940     SDLoc DL(N);
23941
23942     if (isPowerOf2_64(MulAmt2) &&
23943         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23944       // If second multiplifer is pow2, issue it first. We want the multiply by
23945       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23946       // is an add.
23947       std::swap(MulAmt1, MulAmt2);
23948
23949     SDValue NewMul;
23950     if (isPowerOf2_64(MulAmt1))
23951       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23952                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
23953     else
23954       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23955                            DAG.getConstant(MulAmt1, VT));
23956
23957     if (isPowerOf2_64(MulAmt2))
23958       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23959                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
23960     else
23961       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23962                            DAG.getConstant(MulAmt2, VT));
23963
23964     // Do not add new nodes to DAG combiner worklist.
23965     DCI.CombineTo(N, NewMul, false);
23966   }
23967   return SDValue();
23968 }
23969
23970 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23971   SDValue N0 = N->getOperand(0);
23972   SDValue N1 = N->getOperand(1);
23973   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23974   EVT VT = N0.getValueType();
23975
23976   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23977   // since the result of setcc_c is all zero's or all ones.
23978   if (VT.isInteger() && !VT.isVector() &&
23979       N1C && N0.getOpcode() == ISD::AND &&
23980       N0.getOperand(1).getOpcode() == ISD::Constant) {
23981     SDValue N00 = N0.getOperand(0);
23982     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23983         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23984           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23985          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23986       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23987       APInt ShAmt = N1C->getAPIntValue();
23988       Mask = Mask.shl(ShAmt);
23989       if (Mask != 0)
23990         return DAG.getNode(ISD::AND, SDLoc(N), VT,
23991                            N00, DAG.getConstant(Mask, VT));
23992     }
23993   }
23994
23995   // Hardware support for vector shifts is sparse which makes us scalarize the
23996   // vector operations in many cases. Also, on sandybridge ADD is faster than
23997   // shl.
23998   // (shl V, 1) -> add V,V
23999   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24000     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24001       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24002       // We shift all of the values by one. In many cases we do not have
24003       // hardware support for this operation. This is better expressed as an ADD
24004       // of two values.
24005       if (N1SplatC->getZExtValue() == 1)
24006         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24007     }
24008
24009   return SDValue();
24010 }
24011
24012 /// \brief Returns a vector of 0s if the node in input is a vector logical
24013 /// shift by a constant amount which is known to be bigger than or equal
24014 /// to the vector element size in bits.
24015 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24016                                       const X86Subtarget *Subtarget) {
24017   EVT VT = N->getValueType(0);
24018
24019   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24020       (!Subtarget->hasInt256() ||
24021        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24022     return SDValue();
24023
24024   SDValue Amt = N->getOperand(1);
24025   SDLoc DL(N);
24026   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24027     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24028       APInt ShiftAmt = AmtSplat->getAPIntValue();
24029       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24030
24031       // SSE2/AVX2 logical shifts always return a vector of 0s
24032       // if the shift amount is bigger than or equal to
24033       // the element size. The constant shift amount will be
24034       // encoded as a 8-bit immediate.
24035       if (ShiftAmt.trunc(8).uge(MaxAmount))
24036         return getZeroVector(VT, Subtarget, DAG, DL);
24037     }
24038
24039   return SDValue();
24040 }
24041
24042 /// PerformShiftCombine - Combine shifts.
24043 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24044                                    TargetLowering::DAGCombinerInfo &DCI,
24045                                    const X86Subtarget *Subtarget) {
24046   if (N->getOpcode() == ISD::SHL) {
24047     SDValue V = PerformSHLCombine(N, DAG);
24048     if (V.getNode()) return V;
24049   }
24050
24051   if (N->getOpcode() != ISD::SRA) {
24052     // Try to fold this logical shift into a zero vector.
24053     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
24054     if (V.getNode()) return V;
24055   }
24056
24057   return SDValue();
24058 }
24059
24060 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24061 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24062 // and friends.  Likewise for OR -> CMPNEQSS.
24063 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24064                             TargetLowering::DAGCombinerInfo &DCI,
24065                             const X86Subtarget *Subtarget) {
24066   unsigned opcode;
24067
24068   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24069   // we're requiring SSE2 for both.
24070   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24071     SDValue N0 = N->getOperand(0);
24072     SDValue N1 = N->getOperand(1);
24073     SDValue CMP0 = N0->getOperand(1);
24074     SDValue CMP1 = N1->getOperand(1);
24075     SDLoc DL(N);
24076
24077     // The SETCCs should both refer to the same CMP.
24078     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24079       return SDValue();
24080
24081     SDValue CMP00 = CMP0->getOperand(0);
24082     SDValue CMP01 = CMP0->getOperand(1);
24083     EVT     VT    = CMP00.getValueType();
24084
24085     if (VT == MVT::f32 || VT == MVT::f64) {
24086       bool ExpectingFlags = false;
24087       // Check for any users that want flags:
24088       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24089            !ExpectingFlags && UI != UE; ++UI)
24090         switch (UI->getOpcode()) {
24091         default:
24092         case ISD::BR_CC:
24093         case ISD::BRCOND:
24094         case ISD::SELECT:
24095           ExpectingFlags = true;
24096           break;
24097         case ISD::CopyToReg:
24098         case ISD::SIGN_EXTEND:
24099         case ISD::ZERO_EXTEND:
24100         case ISD::ANY_EXTEND:
24101           break;
24102         }
24103
24104       if (!ExpectingFlags) {
24105         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24106         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24107
24108         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24109           X86::CondCode tmp = cc0;
24110           cc0 = cc1;
24111           cc1 = tmp;
24112         }
24113
24114         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24115             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24116           // FIXME: need symbolic constants for these magic numbers.
24117           // See X86ATTInstPrinter.cpp:printSSECC().
24118           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24119           if (Subtarget->hasAVX512()) {
24120             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24121                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
24122             if (N->getValueType(0) != MVT::i1)
24123               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24124                                  FSetCC);
24125             return FSetCC;
24126           }
24127           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24128                                               CMP00.getValueType(), CMP00, CMP01,
24129                                               DAG.getConstant(x86cc, MVT::i8));
24130
24131           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24132           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24133
24134           if (is64BitFP && !Subtarget->is64Bit()) {
24135             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24136             // 64-bit integer, since that's not a legal type. Since
24137             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24138             // bits, but can do this little dance to extract the lowest 32 bits
24139             // and work with those going forward.
24140             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24141                                            OnesOrZeroesF);
24142             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
24143                                            Vector64);
24144             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24145                                         Vector32, DAG.getIntPtrConstant(0));
24146             IntVT = MVT::i32;
24147           }
24148
24149           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
24150           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24151                                       DAG.getConstant(1, IntVT));
24152           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
24153           return OneBitOfTruth;
24154         }
24155       }
24156     }
24157   }
24158   return SDValue();
24159 }
24160
24161 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24162 /// so it can be folded inside ANDNP.
24163 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24164   EVT VT = N->getValueType(0);
24165
24166   // Match direct AllOnes for 128 and 256-bit vectors
24167   if (ISD::isBuildVectorAllOnes(N))
24168     return true;
24169
24170   // Look through a bit convert.
24171   if (N->getOpcode() == ISD::BITCAST)
24172     N = N->getOperand(0).getNode();
24173
24174   // Sometimes the operand may come from a insert_subvector building a 256-bit
24175   // allones vector
24176   if (VT.is256BitVector() &&
24177       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24178     SDValue V1 = N->getOperand(0);
24179     SDValue V2 = N->getOperand(1);
24180
24181     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24182         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24183         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24184         ISD::isBuildVectorAllOnes(V2.getNode()))
24185       return true;
24186   }
24187
24188   return false;
24189 }
24190
24191 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24192 // register. In most cases we actually compare or select YMM-sized registers
24193 // and mixing the two types creates horrible code. This method optimizes
24194 // some of the transition sequences.
24195 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24196                                  TargetLowering::DAGCombinerInfo &DCI,
24197                                  const X86Subtarget *Subtarget) {
24198   EVT VT = N->getValueType(0);
24199   if (!VT.is256BitVector())
24200     return SDValue();
24201
24202   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24203           N->getOpcode() == ISD::ZERO_EXTEND ||
24204           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24205
24206   SDValue Narrow = N->getOperand(0);
24207   EVT NarrowVT = Narrow->getValueType(0);
24208   if (!NarrowVT.is128BitVector())
24209     return SDValue();
24210
24211   if (Narrow->getOpcode() != ISD::XOR &&
24212       Narrow->getOpcode() != ISD::AND &&
24213       Narrow->getOpcode() != ISD::OR)
24214     return SDValue();
24215
24216   SDValue N0  = Narrow->getOperand(0);
24217   SDValue N1  = Narrow->getOperand(1);
24218   SDLoc DL(Narrow);
24219
24220   // The Left side has to be a trunc.
24221   if (N0.getOpcode() != ISD::TRUNCATE)
24222     return SDValue();
24223
24224   // The type of the truncated inputs.
24225   EVT WideVT = N0->getOperand(0)->getValueType(0);
24226   if (WideVT != VT)
24227     return SDValue();
24228
24229   // The right side has to be a 'trunc' or a constant vector.
24230   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24231   ConstantSDNode *RHSConstSplat = nullptr;
24232   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24233     RHSConstSplat = RHSBV->getConstantSplatNode();
24234   if (!RHSTrunc && !RHSConstSplat)
24235     return SDValue();
24236
24237   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24238
24239   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24240     return SDValue();
24241
24242   // Set N0 and N1 to hold the inputs to the new wide operation.
24243   N0 = N0->getOperand(0);
24244   if (RHSConstSplat) {
24245     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24246                      SDValue(RHSConstSplat, 0));
24247     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24248     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24249   } else if (RHSTrunc) {
24250     N1 = N1->getOperand(0);
24251   }
24252
24253   // Generate the wide operation.
24254   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24255   unsigned Opcode = N->getOpcode();
24256   switch (Opcode) {
24257   case ISD::ANY_EXTEND:
24258     return Op;
24259   case ISD::ZERO_EXTEND: {
24260     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24261     APInt Mask = APInt::getAllOnesValue(InBits);
24262     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24263     return DAG.getNode(ISD::AND, DL, VT,
24264                        Op, DAG.getConstant(Mask, VT));
24265   }
24266   case ISD::SIGN_EXTEND:
24267     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24268                        Op, DAG.getValueType(NarrowVT));
24269   default:
24270     llvm_unreachable("Unexpected opcode");
24271   }
24272 }
24273
24274 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24275                                  TargetLowering::DAGCombinerInfo &DCI,
24276                                  const X86Subtarget *Subtarget) {
24277   EVT VT = N->getValueType(0);
24278   if (DCI.isBeforeLegalizeOps())
24279     return SDValue();
24280
24281   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24282   if (R.getNode())
24283     return R;
24284
24285   // Create BEXTR instructions
24286   // BEXTR is ((X >> imm) & (2**size-1))
24287   if (VT == MVT::i32 || VT == MVT::i64) {
24288     SDValue N0 = N->getOperand(0);
24289     SDValue N1 = N->getOperand(1);
24290     SDLoc DL(N);
24291
24292     // Check for BEXTR.
24293     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24294         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24295       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24296       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24297       if (MaskNode && ShiftNode) {
24298         uint64_t Mask = MaskNode->getZExtValue();
24299         uint64_t Shift = ShiftNode->getZExtValue();
24300         if (isMask_64(Mask)) {
24301           uint64_t MaskSize = CountPopulation_64(Mask);
24302           if (Shift + MaskSize <= VT.getSizeInBits())
24303             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24304                                DAG.getConstant(Shift | (MaskSize << 8), VT));
24305         }
24306       }
24307     } // BEXTR
24308
24309     return SDValue();
24310   }
24311
24312   // Want to form ANDNP nodes:
24313   // 1) In the hopes of then easily combining them with OR and AND nodes
24314   //    to form PBLEND/PSIGN.
24315   // 2) To match ANDN packed intrinsics
24316   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24317     return SDValue();
24318
24319   SDValue N0 = N->getOperand(0);
24320   SDValue N1 = N->getOperand(1);
24321   SDLoc DL(N);
24322
24323   // Check LHS for vnot
24324   if (N0.getOpcode() == ISD::XOR &&
24325       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24326       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24327     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24328
24329   // Check RHS for vnot
24330   if (N1.getOpcode() == ISD::XOR &&
24331       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24332       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24333     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24334
24335   return SDValue();
24336 }
24337
24338 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24339                                 TargetLowering::DAGCombinerInfo &DCI,
24340                                 const X86Subtarget *Subtarget) {
24341   if (DCI.isBeforeLegalizeOps())
24342     return SDValue();
24343
24344   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24345   if (R.getNode())
24346     return R;
24347
24348   SDValue N0 = N->getOperand(0);
24349   SDValue N1 = N->getOperand(1);
24350   EVT VT = N->getValueType(0);
24351
24352   // look for psign/blend
24353   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24354     if (!Subtarget->hasSSSE3() ||
24355         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24356       return SDValue();
24357
24358     // Canonicalize pandn to RHS
24359     if (N0.getOpcode() == X86ISD::ANDNP)
24360       std::swap(N0, N1);
24361     // or (and (m, y), (pandn m, x))
24362     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24363       SDValue Mask = N1.getOperand(0);
24364       SDValue X    = N1.getOperand(1);
24365       SDValue Y;
24366       if (N0.getOperand(0) == Mask)
24367         Y = N0.getOperand(1);
24368       if (N0.getOperand(1) == Mask)
24369         Y = N0.getOperand(0);
24370
24371       // Check to see if the mask appeared in both the AND and ANDNP and
24372       if (!Y.getNode())
24373         return SDValue();
24374
24375       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24376       // Look through mask bitcast.
24377       if (Mask.getOpcode() == ISD::BITCAST)
24378         Mask = Mask.getOperand(0);
24379       if (X.getOpcode() == ISD::BITCAST)
24380         X = X.getOperand(0);
24381       if (Y.getOpcode() == ISD::BITCAST)
24382         Y = Y.getOperand(0);
24383
24384       EVT MaskVT = Mask.getValueType();
24385
24386       // Validate that the Mask operand is a vector sra node.
24387       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24388       // there is no psrai.b
24389       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24390       unsigned SraAmt = ~0;
24391       if (Mask.getOpcode() == ISD::SRA) {
24392         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24393           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24394             SraAmt = AmtConst->getZExtValue();
24395       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24396         SDValue SraC = Mask.getOperand(1);
24397         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24398       }
24399       if ((SraAmt + 1) != EltBits)
24400         return SDValue();
24401
24402       SDLoc DL(N);
24403
24404       // Now we know we at least have a plendvb with the mask val.  See if
24405       // we can form a psignb/w/d.
24406       // psign = x.type == y.type == mask.type && y = sub(0, x);
24407       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24408           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24409           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24410         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24411                "Unsupported VT for PSIGN");
24412         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24413         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24414       }
24415       // PBLENDVB only available on SSE 4.1
24416       if (!Subtarget->hasSSE41())
24417         return SDValue();
24418
24419       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24420
24421       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
24422       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
24423       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
24424       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24425       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24426     }
24427   }
24428
24429   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24430     return SDValue();
24431
24432   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24433   MachineFunction &MF = DAG.getMachineFunction();
24434   bool OptForSize = MF.getFunction()->getAttributes().
24435     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
24436
24437   // SHLD/SHRD instructions have lower register pressure, but on some
24438   // platforms they have higher latency than the equivalent
24439   // series of shifts/or that would otherwise be generated.
24440   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24441   // have higher latencies and we are not optimizing for size.
24442   if (!OptForSize && Subtarget->isSHLDSlow())
24443     return SDValue();
24444
24445   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24446     std::swap(N0, N1);
24447   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24448     return SDValue();
24449   if (!N0.hasOneUse() || !N1.hasOneUse())
24450     return SDValue();
24451
24452   SDValue ShAmt0 = N0.getOperand(1);
24453   if (ShAmt0.getValueType() != MVT::i8)
24454     return SDValue();
24455   SDValue ShAmt1 = N1.getOperand(1);
24456   if (ShAmt1.getValueType() != MVT::i8)
24457     return SDValue();
24458   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24459     ShAmt0 = ShAmt0.getOperand(0);
24460   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24461     ShAmt1 = ShAmt1.getOperand(0);
24462
24463   SDLoc DL(N);
24464   unsigned Opc = X86ISD::SHLD;
24465   SDValue Op0 = N0.getOperand(0);
24466   SDValue Op1 = N1.getOperand(0);
24467   if (ShAmt0.getOpcode() == ISD::SUB) {
24468     Opc = X86ISD::SHRD;
24469     std::swap(Op0, Op1);
24470     std::swap(ShAmt0, ShAmt1);
24471   }
24472
24473   unsigned Bits = VT.getSizeInBits();
24474   if (ShAmt1.getOpcode() == ISD::SUB) {
24475     SDValue Sum = ShAmt1.getOperand(0);
24476     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24477       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24478       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24479         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24480       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24481         return DAG.getNode(Opc, DL, VT,
24482                            Op0, Op1,
24483                            DAG.getNode(ISD::TRUNCATE, DL,
24484                                        MVT::i8, ShAmt0));
24485     }
24486   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24487     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24488     if (ShAmt0C &&
24489         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24490       return DAG.getNode(Opc, DL, VT,
24491                          N0.getOperand(0), N1.getOperand(0),
24492                          DAG.getNode(ISD::TRUNCATE, DL,
24493                                        MVT::i8, ShAmt0));
24494   }
24495
24496   return SDValue();
24497 }
24498
24499 // Generate NEG and CMOV for integer abs.
24500 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24501   EVT VT = N->getValueType(0);
24502
24503   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24504   // 8-bit integer abs to NEG and CMOV.
24505   if (VT.isInteger() && VT.getSizeInBits() == 8)
24506     return SDValue();
24507
24508   SDValue N0 = N->getOperand(0);
24509   SDValue N1 = N->getOperand(1);
24510   SDLoc DL(N);
24511
24512   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24513   // and change it to SUB and CMOV.
24514   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24515       N0.getOpcode() == ISD::ADD &&
24516       N0.getOperand(1) == N1 &&
24517       N1.getOpcode() == ISD::SRA &&
24518       N1.getOperand(0) == N0.getOperand(0))
24519     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24520       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24521         // Generate SUB & CMOV.
24522         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24523                                   DAG.getConstant(0, VT), N0.getOperand(0));
24524
24525         SDValue Ops[] = { N0.getOperand(0), Neg,
24526                           DAG.getConstant(X86::COND_GE, MVT::i8),
24527                           SDValue(Neg.getNode(), 1) };
24528         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24529       }
24530   return SDValue();
24531 }
24532
24533 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24534 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24535                                  TargetLowering::DAGCombinerInfo &DCI,
24536                                  const X86Subtarget *Subtarget) {
24537   if (DCI.isBeforeLegalizeOps())
24538     return SDValue();
24539
24540   if (Subtarget->hasCMov()) {
24541     SDValue RV = performIntegerAbsCombine(N, DAG);
24542     if (RV.getNode())
24543       return RV;
24544   }
24545
24546   return SDValue();
24547 }
24548
24549 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24550 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24551                                   TargetLowering::DAGCombinerInfo &DCI,
24552                                   const X86Subtarget *Subtarget) {
24553   LoadSDNode *Ld = cast<LoadSDNode>(N);
24554   EVT RegVT = Ld->getValueType(0);
24555   EVT MemVT = Ld->getMemoryVT();
24556   SDLoc dl(Ld);
24557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24558
24559   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24560   // into two 16-byte operations.
24561   ISD::LoadExtType Ext = Ld->getExtensionType();
24562   unsigned Alignment = Ld->getAlignment();
24563   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24564   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24565       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24566     unsigned NumElems = RegVT.getVectorNumElements();
24567     if (NumElems < 2)
24568       return SDValue();
24569
24570     SDValue Ptr = Ld->getBasePtr();
24571     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
24572
24573     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24574                                   NumElems/2);
24575     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24576                                 Ld->getPointerInfo(), Ld->isVolatile(),
24577                                 Ld->isNonTemporal(), Ld->isInvariant(),
24578                                 Alignment);
24579     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24580     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24581                                 Ld->getPointerInfo(), Ld->isVolatile(),
24582                                 Ld->isNonTemporal(), Ld->isInvariant(),
24583                                 std::min(16U, Alignment));
24584     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24585                              Load1.getValue(1),
24586                              Load2.getValue(1));
24587
24588     SDValue NewVec = DAG.getUNDEF(RegVT);
24589     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24590     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24591     return DCI.CombineTo(N, NewVec, TF, true);
24592   }
24593
24594   return SDValue();
24595 }
24596
24597 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24598 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24599                                    const X86Subtarget *Subtarget) {
24600   StoreSDNode *St = cast<StoreSDNode>(N);
24601   EVT VT = St->getValue().getValueType();
24602   EVT StVT = St->getMemoryVT();
24603   SDLoc dl(St);
24604   SDValue StoredVal = St->getOperand(1);
24605   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24606
24607   // If we are saving a concatenation of two XMM registers and 32-byte stores
24608   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24609   unsigned Alignment = St->getAlignment();
24610   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24611   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24612       StVT == VT && !IsAligned) {
24613     unsigned NumElems = VT.getVectorNumElements();
24614     if (NumElems < 2)
24615       return SDValue();
24616
24617     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24618     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24619
24620     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
24621     SDValue Ptr0 = St->getBasePtr();
24622     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24623
24624     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24625                                 St->getPointerInfo(), St->isVolatile(),
24626                                 St->isNonTemporal(), Alignment);
24627     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24628                                 St->getPointerInfo(), St->isVolatile(),
24629                                 St->isNonTemporal(),
24630                                 std::min(16U, Alignment));
24631     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24632   }
24633
24634   // Optimize trunc store (of multiple scalars) to shuffle and store.
24635   // First, pack all of the elements in one place. Next, store to memory
24636   // in fewer chunks.
24637   if (St->isTruncatingStore() && VT.isVector()) {
24638     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24639     unsigned NumElems = VT.getVectorNumElements();
24640     assert(StVT != VT && "Cannot truncate to the same type");
24641     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24642     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24643
24644     // From, To sizes and ElemCount must be pow of two
24645     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24646     // We are going to use the original vector elt for storing.
24647     // Accumulated smaller vector elements must be a multiple of the store size.
24648     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24649
24650     unsigned SizeRatio  = FromSz / ToSz;
24651
24652     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24653
24654     // Create a type on which we perform the shuffle
24655     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24656             StVT.getScalarType(), NumElems*SizeRatio);
24657
24658     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24659
24660     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
24661     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24662     for (unsigned i = 0; i != NumElems; ++i)
24663       ShuffleVec[i] = i * SizeRatio;
24664
24665     // Can't shuffle using an illegal type.
24666     if (!TLI.isTypeLegal(WideVecVT))
24667       return SDValue();
24668
24669     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24670                                          DAG.getUNDEF(WideVecVT),
24671                                          &ShuffleVec[0]);
24672     // At this point all of the data is stored at the bottom of the
24673     // register. We now need to save it to mem.
24674
24675     // Find the largest store unit
24676     MVT StoreType = MVT::i8;
24677     for (MVT Tp : MVT::integer_valuetypes()) {
24678       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24679         StoreType = Tp;
24680     }
24681
24682     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24683     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24684         (64 <= NumElems * ToSz))
24685       StoreType = MVT::f64;
24686
24687     // Bitcast the original vector into a vector of store-size units
24688     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24689             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24690     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24691     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
24692     SmallVector<SDValue, 8> Chains;
24693     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
24694                                         TLI.getPointerTy());
24695     SDValue Ptr = St->getBasePtr();
24696
24697     // Perform one or more big stores into memory.
24698     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24699       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24700                                    StoreType, ShuffWide,
24701                                    DAG.getIntPtrConstant(i));
24702       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24703                                 St->getPointerInfo(), St->isVolatile(),
24704                                 St->isNonTemporal(), St->getAlignment());
24705       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24706       Chains.push_back(Ch);
24707     }
24708
24709     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24710   }
24711
24712   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24713   // the FP state in cases where an emms may be missing.
24714   // A preferable solution to the general problem is to figure out the right
24715   // places to insert EMMS.  This qualifies as a quick hack.
24716
24717   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24718   if (VT.getSizeInBits() != 64)
24719     return SDValue();
24720
24721   const Function *F = DAG.getMachineFunction().getFunction();
24722   bool NoImplicitFloatOps = F->getAttributes().
24723     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
24724   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
24725                      && Subtarget->hasSSE2();
24726   if ((VT.isVector() ||
24727        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24728       isa<LoadSDNode>(St->getValue()) &&
24729       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24730       St->getChain().hasOneUse() && !St->isVolatile()) {
24731     SDNode* LdVal = St->getValue().getNode();
24732     LoadSDNode *Ld = nullptr;
24733     int TokenFactorIndex = -1;
24734     SmallVector<SDValue, 8> Ops;
24735     SDNode* ChainVal = St->getChain().getNode();
24736     // Must be a store of a load.  We currently handle two cases:  the load
24737     // is a direct child, and it's under an intervening TokenFactor.  It is
24738     // possible to dig deeper under nested TokenFactors.
24739     if (ChainVal == LdVal)
24740       Ld = cast<LoadSDNode>(St->getChain());
24741     else if (St->getValue().hasOneUse() &&
24742              ChainVal->getOpcode() == ISD::TokenFactor) {
24743       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24744         if (ChainVal->getOperand(i).getNode() == LdVal) {
24745           TokenFactorIndex = i;
24746           Ld = cast<LoadSDNode>(St->getValue());
24747         } else
24748           Ops.push_back(ChainVal->getOperand(i));
24749       }
24750     }
24751
24752     if (!Ld || !ISD::isNormalLoad(Ld))
24753       return SDValue();
24754
24755     // If this is not the MMX case, i.e. we are just turning i64 load/store
24756     // into f64 load/store, avoid the transformation if there are multiple
24757     // uses of the loaded value.
24758     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24759       return SDValue();
24760
24761     SDLoc LdDL(Ld);
24762     SDLoc StDL(N);
24763     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24764     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24765     // pair instead.
24766     if (Subtarget->is64Bit() || F64IsLegal) {
24767       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24768       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24769                                   Ld->getPointerInfo(), Ld->isVolatile(),
24770                                   Ld->isNonTemporal(), Ld->isInvariant(),
24771                                   Ld->getAlignment());
24772       SDValue NewChain = NewLd.getValue(1);
24773       if (TokenFactorIndex != -1) {
24774         Ops.push_back(NewChain);
24775         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24776       }
24777       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24778                           St->getPointerInfo(),
24779                           St->isVolatile(), St->isNonTemporal(),
24780                           St->getAlignment());
24781     }
24782
24783     // Otherwise, lower to two pairs of 32-bit loads / stores.
24784     SDValue LoAddr = Ld->getBasePtr();
24785     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24786                                  DAG.getConstant(4, MVT::i32));
24787
24788     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24789                                Ld->getPointerInfo(),
24790                                Ld->isVolatile(), Ld->isNonTemporal(),
24791                                Ld->isInvariant(), Ld->getAlignment());
24792     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24793                                Ld->getPointerInfo().getWithOffset(4),
24794                                Ld->isVolatile(), Ld->isNonTemporal(),
24795                                Ld->isInvariant(),
24796                                MinAlign(Ld->getAlignment(), 4));
24797
24798     SDValue NewChain = LoLd.getValue(1);
24799     if (TokenFactorIndex != -1) {
24800       Ops.push_back(LoLd);
24801       Ops.push_back(HiLd);
24802       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24803     }
24804
24805     LoAddr = St->getBasePtr();
24806     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24807                          DAG.getConstant(4, MVT::i32));
24808
24809     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24810                                 St->getPointerInfo(),
24811                                 St->isVolatile(), St->isNonTemporal(),
24812                                 St->getAlignment());
24813     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24814                                 St->getPointerInfo().getWithOffset(4),
24815                                 St->isVolatile(),
24816                                 St->isNonTemporal(),
24817                                 MinAlign(St->getAlignment(), 4));
24818     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24819   }
24820   return SDValue();
24821 }
24822
24823 /// Return 'true' if this vector operation is "horizontal"
24824 /// and return the operands for the horizontal operation in LHS and RHS.  A
24825 /// horizontal operation performs the binary operation on successive elements
24826 /// of its first operand, then on successive elements of its second operand,
24827 /// returning the resulting values in a vector.  For example, if
24828 ///   A = < float a0, float a1, float a2, float a3 >
24829 /// and
24830 ///   B = < float b0, float b1, float b2, float b3 >
24831 /// then the result of doing a horizontal operation on A and B is
24832 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24833 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24834 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24835 /// set to A, RHS to B, and the routine returns 'true'.
24836 /// Note that the binary operation should have the property that if one of the
24837 /// operands is UNDEF then the result is UNDEF.
24838 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24839   // Look for the following pattern: if
24840   //   A = < float a0, float a1, float a2, float a3 >
24841   //   B = < float b0, float b1, float b2, float b3 >
24842   // and
24843   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24844   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24845   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24846   // which is A horizontal-op B.
24847
24848   // At least one of the operands should be a vector shuffle.
24849   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24850       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24851     return false;
24852
24853   MVT VT = LHS.getSimpleValueType();
24854
24855   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24856          "Unsupported vector type for horizontal add/sub");
24857
24858   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24859   // operate independently on 128-bit lanes.
24860   unsigned NumElts = VT.getVectorNumElements();
24861   unsigned NumLanes = VT.getSizeInBits()/128;
24862   unsigned NumLaneElts = NumElts / NumLanes;
24863   assert((NumLaneElts % 2 == 0) &&
24864          "Vector type should have an even number of elements in each lane");
24865   unsigned HalfLaneElts = NumLaneElts/2;
24866
24867   // View LHS in the form
24868   //   LHS = VECTOR_SHUFFLE A, B, LMask
24869   // If LHS is not a shuffle then pretend it is the shuffle
24870   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24871   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24872   // type VT.
24873   SDValue A, B;
24874   SmallVector<int, 16> LMask(NumElts);
24875   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24876     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24877       A = LHS.getOperand(0);
24878     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24879       B = LHS.getOperand(1);
24880     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24881     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24882   } else {
24883     if (LHS.getOpcode() != ISD::UNDEF)
24884       A = LHS;
24885     for (unsigned i = 0; i != NumElts; ++i)
24886       LMask[i] = i;
24887   }
24888
24889   // Likewise, view RHS in the form
24890   //   RHS = VECTOR_SHUFFLE C, D, RMask
24891   SDValue C, D;
24892   SmallVector<int, 16> RMask(NumElts);
24893   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24894     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24895       C = RHS.getOperand(0);
24896     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24897       D = RHS.getOperand(1);
24898     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24899     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24900   } else {
24901     if (RHS.getOpcode() != ISD::UNDEF)
24902       C = RHS;
24903     for (unsigned i = 0; i != NumElts; ++i)
24904       RMask[i] = i;
24905   }
24906
24907   // Check that the shuffles are both shuffling the same vectors.
24908   if (!(A == C && B == D) && !(A == D && B == C))
24909     return false;
24910
24911   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24912   if (!A.getNode() && !B.getNode())
24913     return false;
24914
24915   // If A and B occur in reverse order in RHS, then "swap" them (which means
24916   // rewriting the mask).
24917   if (A != C)
24918     CommuteVectorShuffleMask(RMask, NumElts);
24919
24920   // At this point LHS and RHS are equivalent to
24921   //   LHS = VECTOR_SHUFFLE A, B, LMask
24922   //   RHS = VECTOR_SHUFFLE A, B, RMask
24923   // Check that the masks correspond to performing a horizontal operation.
24924   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24925     for (unsigned i = 0; i != NumLaneElts; ++i) {
24926       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24927
24928       // Ignore any UNDEF components.
24929       if (LIdx < 0 || RIdx < 0 ||
24930           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24931           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24932         continue;
24933
24934       // Check that successive elements are being operated on.  If not, this is
24935       // not a horizontal operation.
24936       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24937       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24938       if (!(LIdx == Index && RIdx == Index + 1) &&
24939           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24940         return false;
24941     }
24942   }
24943
24944   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24945   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24946   return true;
24947 }
24948
24949 /// Do target-specific dag combines on floating point adds.
24950 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24951                                   const X86Subtarget *Subtarget) {
24952   EVT VT = N->getValueType(0);
24953   SDValue LHS = N->getOperand(0);
24954   SDValue RHS = N->getOperand(1);
24955
24956   // Try to synthesize horizontal adds from adds of shuffles.
24957   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24958        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24959       isHorizontalBinOp(LHS, RHS, true))
24960     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24961   return SDValue();
24962 }
24963
24964 /// Do target-specific dag combines on floating point subs.
24965 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24966                                   const X86Subtarget *Subtarget) {
24967   EVT VT = N->getValueType(0);
24968   SDValue LHS = N->getOperand(0);
24969   SDValue RHS = N->getOperand(1);
24970
24971   // Try to synthesize horizontal subs from subs of shuffles.
24972   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24973        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24974       isHorizontalBinOp(LHS, RHS, false))
24975     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24976   return SDValue();
24977 }
24978
24979 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24980 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24981   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24982   // F[X]OR(0.0, x) -> x
24983   // F[X]OR(x, 0.0) -> x
24984   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24985     if (C->getValueAPF().isPosZero())
24986       return N->getOperand(1);
24987   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24988     if (C->getValueAPF().isPosZero())
24989       return N->getOperand(0);
24990   return SDValue();
24991 }
24992
24993 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24994 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24995   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24996
24997   // Only perform optimizations if UnsafeMath is used.
24998   if (!DAG.getTarget().Options.UnsafeFPMath)
24999     return SDValue();
25000
25001   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25002   // into FMINC and FMAXC, which are Commutative operations.
25003   unsigned NewOp = 0;
25004   switch (N->getOpcode()) {
25005     default: llvm_unreachable("unknown opcode");
25006     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25007     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25008   }
25009
25010   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25011                      N->getOperand(0), N->getOperand(1));
25012 }
25013
25014 /// Do target-specific dag combines on X86ISD::FAND nodes.
25015 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25016   // FAND(0.0, x) -> 0.0
25017   // FAND(x, 0.0) -> 0.0
25018   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25019     if (C->getValueAPF().isPosZero())
25020       return N->getOperand(0);
25021   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25022     if (C->getValueAPF().isPosZero())
25023       return N->getOperand(1);
25024   return SDValue();
25025 }
25026
25027 /// Do target-specific dag combines on X86ISD::FANDN nodes
25028 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25029   // FANDN(x, 0.0) -> 0.0
25030   // FANDN(0.0, x) -> x
25031   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25032     if (C->getValueAPF().isPosZero())
25033       return N->getOperand(1);
25034   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25035     if (C->getValueAPF().isPosZero())
25036       return N->getOperand(1);
25037   return SDValue();
25038 }
25039
25040 static SDValue PerformBTCombine(SDNode *N,
25041                                 SelectionDAG &DAG,
25042                                 TargetLowering::DAGCombinerInfo &DCI) {
25043   // BT ignores high bits in the bit index operand.
25044   SDValue Op1 = N->getOperand(1);
25045   if (Op1.hasOneUse()) {
25046     unsigned BitWidth = Op1.getValueSizeInBits();
25047     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25048     APInt KnownZero, KnownOne;
25049     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25050                                           !DCI.isBeforeLegalizeOps());
25051     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25052     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25053         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25054       DCI.CommitTargetLoweringOpt(TLO);
25055   }
25056   return SDValue();
25057 }
25058
25059 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25060   SDValue Op = N->getOperand(0);
25061   if (Op.getOpcode() == ISD::BITCAST)
25062     Op = Op.getOperand(0);
25063   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25064   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25065       VT.getVectorElementType().getSizeInBits() ==
25066       OpVT.getVectorElementType().getSizeInBits()) {
25067     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25068   }
25069   return SDValue();
25070 }
25071
25072 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25073                                                const X86Subtarget *Subtarget) {
25074   EVT VT = N->getValueType(0);
25075   if (!VT.isVector())
25076     return SDValue();
25077
25078   SDValue N0 = N->getOperand(0);
25079   SDValue N1 = N->getOperand(1);
25080   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25081   SDLoc dl(N);
25082
25083   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25084   // both SSE and AVX2 since there is no sign-extended shift right
25085   // operation on a vector with 64-bit elements.
25086   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25087   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25088   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25089       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25090     SDValue N00 = N0.getOperand(0);
25091
25092     // EXTLOAD has a better solution on AVX2,
25093     // it may be replaced with X86ISD::VSEXT node.
25094     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25095       if (!ISD::isNormalLoad(N00.getNode()))
25096         return SDValue();
25097
25098     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25099         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25100                                   N00, N1);
25101       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25102     }
25103   }
25104   return SDValue();
25105 }
25106
25107 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25108                                   TargetLowering::DAGCombinerInfo &DCI,
25109                                   const X86Subtarget *Subtarget) {
25110   SDValue N0 = N->getOperand(0);
25111   EVT VT = N->getValueType(0);
25112
25113   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25114   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25115   // This exposes the sext to the sdivrem lowering, so that it directly extends
25116   // from AH (which we otherwise need to do contortions to access).
25117   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25118       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
25119     SDLoc dl(N);
25120     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25121     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
25122                             N0.getOperand(0), N0.getOperand(1));
25123     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25124     return R.getValue(1);
25125   }
25126
25127   if (!DCI.isBeforeLegalizeOps())
25128     return SDValue();
25129
25130   if (!Subtarget->hasFp256())
25131     return SDValue();
25132
25133   if (VT.isVector() && VT.getSizeInBits() == 256) {
25134     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25135     if (R.getNode())
25136       return R;
25137   }
25138
25139   return SDValue();
25140 }
25141
25142 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25143                                  const X86Subtarget* Subtarget) {
25144   SDLoc dl(N);
25145   EVT VT = N->getValueType(0);
25146
25147   // Let legalize expand this if it isn't a legal type yet.
25148   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25149     return SDValue();
25150
25151   EVT ScalarVT = VT.getScalarType();
25152   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25153       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
25154     return SDValue();
25155
25156   SDValue A = N->getOperand(0);
25157   SDValue B = N->getOperand(1);
25158   SDValue C = N->getOperand(2);
25159
25160   bool NegA = (A.getOpcode() == ISD::FNEG);
25161   bool NegB = (B.getOpcode() == ISD::FNEG);
25162   bool NegC = (C.getOpcode() == ISD::FNEG);
25163
25164   // Negative multiplication when NegA xor NegB
25165   bool NegMul = (NegA != NegB);
25166   if (NegA)
25167     A = A.getOperand(0);
25168   if (NegB)
25169     B = B.getOperand(0);
25170   if (NegC)
25171     C = C.getOperand(0);
25172
25173   unsigned Opcode;
25174   if (!NegMul)
25175     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25176   else
25177     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25178
25179   return DAG.getNode(Opcode, dl, VT, A, B, C);
25180 }
25181
25182 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25183                                   TargetLowering::DAGCombinerInfo &DCI,
25184                                   const X86Subtarget *Subtarget) {
25185   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25186   //           (and (i32 x86isd::setcc_carry), 1)
25187   // This eliminates the zext. This transformation is necessary because
25188   // ISD::SETCC is always legalized to i8.
25189   SDLoc dl(N);
25190   SDValue N0 = N->getOperand(0);
25191   EVT VT = N->getValueType(0);
25192
25193   if (N0.getOpcode() == ISD::AND &&
25194       N0.hasOneUse() &&
25195       N0.getOperand(0).hasOneUse()) {
25196     SDValue N00 = N0.getOperand(0);
25197     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25198       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25199       if (!C || C->getZExtValue() != 1)
25200         return SDValue();
25201       return DAG.getNode(ISD::AND, dl, VT,
25202                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25203                                      N00.getOperand(0), N00.getOperand(1)),
25204                          DAG.getConstant(1, VT));
25205     }
25206   }
25207
25208   if (N0.getOpcode() == ISD::TRUNCATE &&
25209       N0.hasOneUse() &&
25210       N0.getOperand(0).hasOneUse()) {
25211     SDValue N00 = N0.getOperand(0);
25212     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25213       return DAG.getNode(ISD::AND, dl, VT,
25214                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25215                                      N00.getOperand(0), N00.getOperand(1)),
25216                          DAG.getConstant(1, VT));
25217     }
25218   }
25219   if (VT.is256BitVector()) {
25220     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25221     if (R.getNode())
25222       return R;
25223   }
25224
25225   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25226   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25227   // This exposes the zext to the udivrem lowering, so that it directly extends
25228   // from AH (which we otherwise need to do contortions to access).
25229   if (N0.getOpcode() == ISD::UDIVREM &&
25230       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25231       (VT == MVT::i32 || VT == MVT::i64)) {
25232     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25233     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25234                             N0.getOperand(0), N0.getOperand(1));
25235     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25236     return R.getValue(1);
25237   }
25238
25239   return SDValue();
25240 }
25241
25242 // Optimize x == -y --> x+y == 0
25243 //          x != -y --> x+y != 0
25244 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25245                                       const X86Subtarget* Subtarget) {
25246   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25247   SDValue LHS = N->getOperand(0);
25248   SDValue RHS = N->getOperand(1);
25249   EVT VT = N->getValueType(0);
25250   SDLoc DL(N);
25251
25252   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25253     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25254       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25255         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25256                                    LHS.getValueType(), RHS, LHS.getOperand(1));
25257         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25258                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25259       }
25260   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25261     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25262       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25263         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25264                                    RHS.getValueType(), LHS, RHS.getOperand(1));
25265         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25266                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25267       }
25268
25269   if (VT.getScalarType() == MVT::i1) {
25270     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25271       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25272     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
25273     if (!IsSEXT0 && !IsVZero0)
25274       return SDValue();
25275     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
25276       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25277     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25278
25279     if (!IsSEXT1 && !IsVZero1)
25280       return SDValue();
25281
25282     if (IsSEXT0 && IsVZero1) {
25283       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
25284       if (CC == ISD::SETEQ)
25285         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25286       return LHS.getOperand(0);
25287     }
25288     if (IsSEXT1 && IsVZero0) {
25289       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
25290       if (CC == ISD::SETEQ)
25291         return DAG.getNOT(DL, RHS.getOperand(0), VT);
25292       return RHS.getOperand(0);
25293     }
25294   }
25295
25296   return SDValue();
25297 }
25298
25299 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25300                                       const X86Subtarget *Subtarget) {
25301   SDLoc dl(N);
25302   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25303   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25304          "X86insertps is only defined for v4x32");
25305
25306   SDValue Ld = N->getOperand(1);
25307   if (MayFoldLoad(Ld)) {
25308     // Extract the countS bits from the immediate so we can get the proper
25309     // address when narrowing the vector load to a specific element.
25310     // When the second source op is a memory address, interps doesn't use
25311     // countS and just gets an f32 from that address.
25312     unsigned DestIndex =
25313         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25314     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25315   } else
25316     return SDValue();
25317
25318   // Create this as a scalar to vector to match the instruction pattern.
25319   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25320   // countS bits are ignored when loading from memory on insertps, which
25321   // means we don't need to explicitly set them to 0.
25322   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25323                      LoadScalarToVector, N->getOperand(2));
25324 }
25325
25326 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25327 // as "sbb reg,reg", since it can be extended without zext and produces
25328 // an all-ones bit which is more useful than 0/1 in some cases.
25329 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25330                                MVT VT) {
25331   if (VT == MVT::i8)
25332     return DAG.getNode(ISD::AND, DL, VT,
25333                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25334                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
25335                        DAG.getConstant(1, VT));
25336   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25337   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25338                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25339                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
25340 }
25341
25342 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25343 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25344                                    TargetLowering::DAGCombinerInfo &DCI,
25345                                    const X86Subtarget *Subtarget) {
25346   SDLoc DL(N);
25347   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25348   SDValue EFLAGS = N->getOperand(1);
25349
25350   if (CC == X86::COND_A) {
25351     // Try to convert COND_A into COND_B in an attempt to facilitate
25352     // materializing "setb reg".
25353     //
25354     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25355     // cannot take an immediate as its first operand.
25356     //
25357     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25358         EFLAGS.getValueType().isInteger() &&
25359         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25360       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25361                                    EFLAGS.getNode()->getVTList(),
25362                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25363       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25364       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25365     }
25366   }
25367
25368   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25369   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25370   // cases.
25371   if (CC == X86::COND_B)
25372     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25373
25374   SDValue Flags;
25375
25376   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25377   if (Flags.getNode()) {
25378     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25379     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25380   }
25381
25382   return SDValue();
25383 }
25384
25385 // Optimize branch condition evaluation.
25386 //
25387 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25388                                     TargetLowering::DAGCombinerInfo &DCI,
25389                                     const X86Subtarget *Subtarget) {
25390   SDLoc DL(N);
25391   SDValue Chain = N->getOperand(0);
25392   SDValue Dest = N->getOperand(1);
25393   SDValue EFLAGS = N->getOperand(3);
25394   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25395
25396   SDValue Flags;
25397
25398   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25399   if (Flags.getNode()) {
25400     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25401     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25402                        Flags);
25403   }
25404
25405   return SDValue();
25406 }
25407
25408 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25409                                                          SelectionDAG &DAG) {
25410   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25411   // optimize away operation when it's from a constant.
25412   //
25413   // The general transformation is:
25414   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25415   //       AND(VECTOR_CMP(x,y), constant2)
25416   //    constant2 = UNARYOP(constant)
25417
25418   // Early exit if this isn't a vector operation, the operand of the
25419   // unary operation isn't a bitwise AND, or if the sizes of the operations
25420   // aren't the same.
25421   EVT VT = N->getValueType(0);
25422   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25423       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25424       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25425     return SDValue();
25426
25427   // Now check that the other operand of the AND is a constant. We could
25428   // make the transformation for non-constant splats as well, but it's unclear
25429   // that would be a benefit as it would not eliminate any operations, just
25430   // perform one more step in scalar code before moving to the vector unit.
25431   if (BuildVectorSDNode *BV =
25432           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25433     // Bail out if the vector isn't a constant.
25434     if (!BV->isConstant())
25435       return SDValue();
25436
25437     // Everything checks out. Build up the new and improved node.
25438     SDLoc DL(N);
25439     EVT IntVT = BV->getValueType(0);
25440     // Create a new constant of the appropriate type for the transformed
25441     // DAG.
25442     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25443     // The AND node needs bitcasts to/from an integer vector type around it.
25444     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
25445     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25446                                  N->getOperand(0)->getOperand(0), MaskConst);
25447     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
25448     return Res;
25449   }
25450
25451   return SDValue();
25452 }
25453
25454 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25455                                         const X86TargetLowering *XTLI) {
25456   // First try to optimize away the conversion entirely when it's
25457   // conditionally from a constant. Vectors only.
25458   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
25459   if (Res != SDValue())
25460     return Res;
25461
25462   // Now move on to more general possibilities.
25463   SDValue Op0 = N->getOperand(0);
25464   EVT InVT = Op0->getValueType(0);
25465
25466   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
25467   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
25468     SDLoc dl(N);
25469     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
25470     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25471     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
25472   }
25473
25474   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25475   // a 32-bit target where SSE doesn't support i64->FP operations.
25476   if (Op0.getOpcode() == ISD::LOAD) {
25477     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25478     EVT VT = Ld->getValueType(0);
25479     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
25480         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25481         !XTLI->getSubtarget()->is64Bit() &&
25482         VT == MVT::i64) {
25483       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
25484                                           Ld->getChain(), Op0, DAG);
25485       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25486       return FILDChain;
25487     }
25488   }
25489   return SDValue();
25490 }
25491
25492 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25493 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25494                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25495   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25496   // the result is either zero or one (depending on the input carry bit).
25497   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25498   if (X86::isZeroNode(N->getOperand(0)) &&
25499       X86::isZeroNode(N->getOperand(1)) &&
25500       // We don't have a good way to replace an EFLAGS use, so only do this when
25501       // dead right now.
25502       SDValue(N, 1).use_empty()) {
25503     SDLoc DL(N);
25504     EVT VT = N->getValueType(0);
25505     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
25506     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25507                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25508                                            DAG.getConstant(X86::COND_B,MVT::i8),
25509                                            N->getOperand(2)),
25510                                DAG.getConstant(1, VT));
25511     return DCI.CombineTo(N, Res1, CarryOut);
25512   }
25513
25514   return SDValue();
25515 }
25516
25517 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25518 //      (add Y, (setne X, 0)) -> sbb -1, Y
25519 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25520 //      (sub (setne X, 0), Y) -> adc -1, Y
25521 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25522   SDLoc DL(N);
25523
25524   // Look through ZExts.
25525   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25526   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25527     return SDValue();
25528
25529   SDValue SetCC = Ext.getOperand(0);
25530   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25531     return SDValue();
25532
25533   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25534   if (CC != X86::COND_E && CC != X86::COND_NE)
25535     return SDValue();
25536
25537   SDValue Cmp = SetCC.getOperand(1);
25538   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25539       !X86::isZeroNode(Cmp.getOperand(1)) ||
25540       !Cmp.getOperand(0).getValueType().isInteger())
25541     return SDValue();
25542
25543   SDValue CmpOp0 = Cmp.getOperand(0);
25544   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25545                                DAG.getConstant(1, CmpOp0.getValueType()));
25546
25547   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25548   if (CC == X86::COND_NE)
25549     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25550                        DL, OtherVal.getValueType(), OtherVal,
25551                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
25552   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25553                      DL, OtherVal.getValueType(), OtherVal,
25554                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
25555 }
25556
25557 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25558 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25559                                  const X86Subtarget *Subtarget) {
25560   EVT VT = N->getValueType(0);
25561   SDValue Op0 = N->getOperand(0);
25562   SDValue Op1 = N->getOperand(1);
25563
25564   // Try to synthesize horizontal adds from adds of shuffles.
25565   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25566        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25567       isHorizontalBinOp(Op0, Op1, true))
25568     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25569
25570   return OptimizeConditionalInDecrement(N, DAG);
25571 }
25572
25573 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25574                                  const X86Subtarget *Subtarget) {
25575   SDValue Op0 = N->getOperand(0);
25576   SDValue Op1 = N->getOperand(1);
25577
25578   // X86 can't encode an immediate LHS of a sub. See if we can push the
25579   // negation into a preceding instruction.
25580   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25581     // If the RHS of the sub is a XOR with one use and a constant, invert the
25582     // immediate. Then add one to the LHS of the sub so we can turn
25583     // X-Y -> X+~Y+1, saving one register.
25584     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25585         isa<ConstantSDNode>(Op1.getOperand(1))) {
25586       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25587       EVT VT = Op0.getValueType();
25588       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25589                                    Op1.getOperand(0),
25590                                    DAG.getConstant(~XorC, VT));
25591       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25592                          DAG.getConstant(C->getAPIntValue()+1, VT));
25593     }
25594   }
25595
25596   // Try to synthesize horizontal adds from adds of shuffles.
25597   EVT VT = N->getValueType(0);
25598   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25599        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25600       isHorizontalBinOp(Op0, Op1, true))
25601     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25602
25603   return OptimizeConditionalInDecrement(N, DAG);
25604 }
25605
25606 /// performVZEXTCombine - Performs build vector combines
25607 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25608                                    TargetLowering::DAGCombinerInfo &DCI,
25609                                    const X86Subtarget *Subtarget) {
25610   SDLoc DL(N);
25611   MVT VT = N->getSimpleValueType(0);
25612   SDValue Op = N->getOperand(0);
25613   MVT OpVT = Op.getSimpleValueType();
25614   MVT OpEltVT = OpVT.getVectorElementType();
25615   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25616
25617   // (vzext (bitcast (vzext (x)) -> (vzext x)
25618   SDValue V = Op;
25619   while (V.getOpcode() == ISD::BITCAST)
25620     V = V.getOperand(0);
25621
25622   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25623     MVT InnerVT = V.getSimpleValueType();
25624     MVT InnerEltVT = InnerVT.getVectorElementType();
25625
25626     // If the element sizes match exactly, we can just do one larger vzext. This
25627     // is always an exact type match as vzext operates on integer types.
25628     if (OpEltVT == InnerEltVT) {
25629       assert(OpVT == InnerVT && "Types must match for vzext!");
25630       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25631     }
25632
25633     // The only other way we can combine them is if only a single element of the
25634     // inner vzext is used in the input to the outer vzext.
25635     if (InnerEltVT.getSizeInBits() < InputBits)
25636       return SDValue();
25637
25638     // In this case, the inner vzext is completely dead because we're going to
25639     // only look at bits inside of the low element. Just do the outer vzext on
25640     // a bitcast of the input to the inner.
25641     return DAG.getNode(X86ISD::VZEXT, DL, VT,
25642                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
25643   }
25644
25645   // Check if we can bypass extracting and re-inserting an element of an input
25646   // vector. Essentialy:
25647   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25648   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25649       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25650       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25651     SDValue ExtractedV = V.getOperand(0);
25652     SDValue OrigV = ExtractedV.getOperand(0);
25653     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25654       if (ExtractIdx->getZExtValue() == 0) {
25655         MVT OrigVT = OrigV.getSimpleValueType();
25656         // Extract a subvector if necessary...
25657         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25658           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25659           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25660                                     OrigVT.getVectorNumElements() / Ratio);
25661           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25662                               DAG.getIntPtrConstant(0));
25663         }
25664         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
25665         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25666       }
25667   }
25668
25669   return SDValue();
25670 }
25671
25672 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25673                                              DAGCombinerInfo &DCI) const {
25674   SelectionDAG &DAG = DCI.DAG;
25675   switch (N->getOpcode()) {
25676   default: break;
25677   case ISD::EXTRACT_VECTOR_ELT:
25678     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25679   case ISD::VSELECT:
25680   case ISD::SELECT:
25681   case X86ISD::SHRUNKBLEND:
25682     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25683   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25684   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25685   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25686   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25687   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25688   case ISD::SHL:
25689   case ISD::SRA:
25690   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25691   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25692   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25693   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25694   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25695   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25696   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
25697   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25698   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25699   case X86ISD::FXOR:
25700   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25701   case X86ISD::FMIN:
25702   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25703   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25704   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25705   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25706   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25707   case ISD::ANY_EXTEND:
25708   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25709   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25710   case ISD::SIGN_EXTEND_INREG:
25711     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25712   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
25713   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25714   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25715   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25716   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25717   case X86ISD::SHUFP:       // Handle all target specific shuffles
25718   case X86ISD::PALIGNR:
25719   case X86ISD::UNPCKH:
25720   case X86ISD::UNPCKL:
25721   case X86ISD::MOVHLPS:
25722   case X86ISD::MOVLHPS:
25723   case X86ISD::PSHUFB:
25724   case X86ISD::PSHUFD:
25725   case X86ISD::PSHUFHW:
25726   case X86ISD::PSHUFLW:
25727   case X86ISD::MOVSS:
25728   case X86ISD::MOVSD:
25729   case X86ISD::VPERMILPI:
25730   case X86ISD::VPERM2X128:
25731   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25732   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25733   case ISD::INTRINSIC_WO_CHAIN:
25734     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25735   case X86ISD::INSERTPS:
25736     return PerformINSERTPSCombine(N, DAG, Subtarget);
25737   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
25738   }
25739
25740   return SDValue();
25741 }
25742
25743 /// isTypeDesirableForOp - Return true if the target has native support for
25744 /// the specified value type and it is 'desirable' to use the type for the
25745 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25746 /// instruction encodings are longer and some i16 instructions are slow.
25747 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25748   if (!isTypeLegal(VT))
25749     return false;
25750   if (VT != MVT::i16)
25751     return true;
25752
25753   switch (Opc) {
25754   default:
25755     return true;
25756   case ISD::LOAD:
25757   case ISD::SIGN_EXTEND:
25758   case ISD::ZERO_EXTEND:
25759   case ISD::ANY_EXTEND:
25760   case ISD::SHL:
25761   case ISD::SRL:
25762   case ISD::SUB:
25763   case ISD::ADD:
25764   case ISD::MUL:
25765   case ISD::AND:
25766   case ISD::OR:
25767   case ISD::XOR:
25768     return false;
25769   }
25770 }
25771
25772 /// IsDesirableToPromoteOp - This method query the target whether it is
25773 /// beneficial for dag combiner to promote the specified node. If true, it
25774 /// should return the desired promotion type by reference.
25775 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25776   EVT VT = Op.getValueType();
25777   if (VT != MVT::i16)
25778     return false;
25779
25780   bool Promote = false;
25781   bool Commute = false;
25782   switch (Op.getOpcode()) {
25783   default: break;
25784   case ISD::LOAD: {
25785     LoadSDNode *LD = cast<LoadSDNode>(Op);
25786     // If the non-extending load has a single use and it's not live out, then it
25787     // might be folded.
25788     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25789                                                      Op.hasOneUse()*/) {
25790       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25791              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25792         // The only case where we'd want to promote LOAD (rather then it being
25793         // promoted as an operand is when it's only use is liveout.
25794         if (UI->getOpcode() != ISD::CopyToReg)
25795           return false;
25796       }
25797     }
25798     Promote = true;
25799     break;
25800   }
25801   case ISD::SIGN_EXTEND:
25802   case ISD::ZERO_EXTEND:
25803   case ISD::ANY_EXTEND:
25804     Promote = true;
25805     break;
25806   case ISD::SHL:
25807   case ISD::SRL: {
25808     SDValue N0 = Op.getOperand(0);
25809     // Look out for (store (shl (load), x)).
25810     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25811       return false;
25812     Promote = true;
25813     break;
25814   }
25815   case ISD::ADD:
25816   case ISD::MUL:
25817   case ISD::AND:
25818   case ISD::OR:
25819   case ISD::XOR:
25820     Commute = true;
25821     // fallthrough
25822   case ISD::SUB: {
25823     SDValue N0 = Op.getOperand(0);
25824     SDValue N1 = Op.getOperand(1);
25825     if (!Commute && MayFoldLoad(N1))
25826       return false;
25827     // Avoid disabling potential load folding opportunities.
25828     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25829       return false;
25830     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25831       return false;
25832     Promote = true;
25833   }
25834   }
25835
25836   PVT = MVT::i32;
25837   return Promote;
25838 }
25839
25840 //===----------------------------------------------------------------------===//
25841 //                           X86 Inline Assembly Support
25842 //===----------------------------------------------------------------------===//
25843
25844 namespace {
25845   // Helper to match a string separated by whitespace.
25846   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
25847     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
25848
25849     for (unsigned i = 0, e = args.size(); i != e; ++i) {
25850       StringRef piece(*args[i]);
25851       if (!s.startswith(piece)) // Check if the piece matches.
25852         return false;
25853
25854       s = s.substr(piece.size());
25855       StringRef::size_type pos = s.find_first_not_of(" \t");
25856       if (pos == 0) // We matched a prefix.
25857         return false;
25858
25859       s = s.substr(pos);
25860     }
25861
25862     return s.empty();
25863   }
25864   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
25865 }
25866
25867 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25868
25869   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25870     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25871         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25872         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25873
25874       if (AsmPieces.size() == 3)
25875         return true;
25876       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25877         return true;
25878     }
25879   }
25880   return false;
25881 }
25882
25883 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25884   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25885
25886   std::string AsmStr = IA->getAsmString();
25887
25888   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25889   if (!Ty || Ty->getBitWidth() % 16 != 0)
25890     return false;
25891
25892   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25893   SmallVector<StringRef, 4> AsmPieces;
25894   SplitString(AsmStr, AsmPieces, ";\n");
25895
25896   switch (AsmPieces.size()) {
25897   default: return false;
25898   case 1:
25899     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25900     // we will turn this bswap into something that will be lowered to logical
25901     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25902     // lower so don't worry about this.
25903     // bswap $0
25904     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
25905         matchAsm(AsmPieces[0], "bswapl", "$0") ||
25906         matchAsm(AsmPieces[0], "bswapq", "$0") ||
25907         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
25908         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
25909         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
25910       // No need to check constraints, nothing other than the equivalent of
25911       // "=r,0" would be valid here.
25912       return IntrinsicLowering::LowerToByteSwap(CI);
25913     }
25914
25915     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25916     if (CI->getType()->isIntegerTy(16) &&
25917         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25918         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
25919          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
25920       AsmPieces.clear();
25921       const std::string &ConstraintsStr = IA->getConstraintString();
25922       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25923       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25924       if (clobbersFlagRegisters(AsmPieces))
25925         return IntrinsicLowering::LowerToByteSwap(CI);
25926     }
25927     break;
25928   case 3:
25929     if (CI->getType()->isIntegerTy(32) &&
25930         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25931         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
25932         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
25933         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
25934       AsmPieces.clear();
25935       const std::string &ConstraintsStr = IA->getConstraintString();
25936       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25937       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25938       if (clobbersFlagRegisters(AsmPieces))
25939         return IntrinsicLowering::LowerToByteSwap(CI);
25940     }
25941
25942     if (CI->getType()->isIntegerTy(64)) {
25943       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25944       if (Constraints.size() >= 2 &&
25945           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25946           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25947         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25948         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
25949             matchAsm(AsmPieces[1], "bswap", "%edx") &&
25950             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
25951           return IntrinsicLowering::LowerToByteSwap(CI);
25952       }
25953     }
25954     break;
25955   }
25956   return false;
25957 }
25958
25959 /// getConstraintType - Given a constraint letter, return the type of
25960 /// constraint it is for this target.
25961 X86TargetLowering::ConstraintType
25962 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
25963   if (Constraint.size() == 1) {
25964     switch (Constraint[0]) {
25965     case 'R':
25966     case 'q':
25967     case 'Q':
25968     case 'f':
25969     case 't':
25970     case 'u':
25971     case 'y':
25972     case 'x':
25973     case 'Y':
25974     case 'l':
25975       return C_RegisterClass;
25976     case 'a':
25977     case 'b':
25978     case 'c':
25979     case 'd':
25980     case 'S':
25981     case 'D':
25982     case 'A':
25983       return C_Register;
25984     case 'I':
25985     case 'J':
25986     case 'K':
25987     case 'L':
25988     case 'M':
25989     case 'N':
25990     case 'G':
25991     case 'C':
25992     case 'e':
25993     case 'Z':
25994       return C_Other;
25995     default:
25996       break;
25997     }
25998   }
25999   return TargetLowering::getConstraintType(Constraint);
26000 }
26001
26002 /// Examine constraint type and operand type and determine a weight value.
26003 /// This object must already have been set up with the operand type
26004 /// and the current alternative constraint selected.
26005 TargetLowering::ConstraintWeight
26006   X86TargetLowering::getSingleConstraintMatchWeight(
26007     AsmOperandInfo &info, const char *constraint) const {
26008   ConstraintWeight weight = CW_Invalid;
26009   Value *CallOperandVal = info.CallOperandVal;
26010     // If we don't have a value, we can't do a match,
26011     // but allow it at the lowest weight.
26012   if (!CallOperandVal)
26013     return CW_Default;
26014   Type *type = CallOperandVal->getType();
26015   // Look at the constraint type.
26016   switch (*constraint) {
26017   default:
26018     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26019   case 'R':
26020   case 'q':
26021   case 'Q':
26022   case 'a':
26023   case 'b':
26024   case 'c':
26025   case 'd':
26026   case 'S':
26027   case 'D':
26028   case 'A':
26029     if (CallOperandVal->getType()->isIntegerTy())
26030       weight = CW_SpecificReg;
26031     break;
26032   case 'f':
26033   case 't':
26034   case 'u':
26035     if (type->isFloatingPointTy())
26036       weight = CW_SpecificReg;
26037     break;
26038   case 'y':
26039     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26040       weight = CW_SpecificReg;
26041     break;
26042   case 'x':
26043   case 'Y':
26044     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26045         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26046       weight = CW_Register;
26047     break;
26048   case 'I':
26049     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26050       if (C->getZExtValue() <= 31)
26051         weight = CW_Constant;
26052     }
26053     break;
26054   case 'J':
26055     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26056       if (C->getZExtValue() <= 63)
26057         weight = CW_Constant;
26058     }
26059     break;
26060   case 'K':
26061     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26062       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26063         weight = CW_Constant;
26064     }
26065     break;
26066   case 'L':
26067     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26068       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26069         weight = CW_Constant;
26070     }
26071     break;
26072   case 'M':
26073     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26074       if (C->getZExtValue() <= 3)
26075         weight = CW_Constant;
26076     }
26077     break;
26078   case 'N':
26079     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26080       if (C->getZExtValue() <= 0xff)
26081         weight = CW_Constant;
26082     }
26083     break;
26084   case 'G':
26085   case 'C':
26086     if (dyn_cast<ConstantFP>(CallOperandVal)) {
26087       weight = CW_Constant;
26088     }
26089     break;
26090   case 'e':
26091     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26092       if ((C->getSExtValue() >= -0x80000000LL) &&
26093           (C->getSExtValue() <= 0x7fffffffLL))
26094         weight = CW_Constant;
26095     }
26096     break;
26097   case 'Z':
26098     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26099       if (C->getZExtValue() <= 0xffffffff)
26100         weight = CW_Constant;
26101     }
26102     break;
26103   }
26104   return weight;
26105 }
26106
26107 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26108 /// with another that has more specific requirements based on the type of the
26109 /// corresponding operand.
26110 const char *X86TargetLowering::
26111 LowerXConstraint(EVT ConstraintVT) const {
26112   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26113   // 'f' like normal targets.
26114   if (ConstraintVT.isFloatingPoint()) {
26115     if (Subtarget->hasSSE2())
26116       return "Y";
26117     if (Subtarget->hasSSE1())
26118       return "x";
26119   }
26120
26121   return TargetLowering::LowerXConstraint(ConstraintVT);
26122 }
26123
26124 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26125 /// vector.  If it is invalid, don't add anything to Ops.
26126 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26127                                                      std::string &Constraint,
26128                                                      std::vector<SDValue>&Ops,
26129                                                      SelectionDAG &DAG) const {
26130   SDValue Result;
26131
26132   // Only support length 1 constraints for now.
26133   if (Constraint.length() > 1) return;
26134
26135   char ConstraintLetter = Constraint[0];
26136   switch (ConstraintLetter) {
26137   default: break;
26138   case 'I':
26139     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26140       if (C->getZExtValue() <= 31) {
26141         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26142         break;
26143       }
26144     }
26145     return;
26146   case 'J':
26147     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26148       if (C->getZExtValue() <= 63) {
26149         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26150         break;
26151       }
26152     }
26153     return;
26154   case 'K':
26155     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26156       if (isInt<8>(C->getSExtValue())) {
26157         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26158         break;
26159       }
26160     }
26161     return;
26162   case 'N':
26163     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26164       if (C->getZExtValue() <= 255) {
26165         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26166         break;
26167       }
26168     }
26169     return;
26170   case 'e': {
26171     // 32-bit signed value
26172     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26173       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26174                                            C->getSExtValue())) {
26175         // Widen to 64 bits here to get it sign extended.
26176         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
26177         break;
26178       }
26179     // FIXME gcc accepts some relocatable values here too, but only in certain
26180     // memory models; it's complicated.
26181     }
26182     return;
26183   }
26184   case 'Z': {
26185     // 32-bit unsigned value
26186     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26187       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26188                                            C->getZExtValue())) {
26189         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26190         break;
26191       }
26192     }
26193     // FIXME gcc accepts some relocatable values here too, but only in certain
26194     // memory models; it's complicated.
26195     return;
26196   }
26197   case 'i': {
26198     // Literal immediates are always ok.
26199     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26200       // Widen to 64 bits here to get it sign extended.
26201       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
26202       break;
26203     }
26204
26205     // In any sort of PIC mode addresses need to be computed at runtime by
26206     // adding in a register or some sort of table lookup.  These can't
26207     // be used as immediates.
26208     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26209       return;
26210
26211     // If we are in non-pic codegen mode, we allow the address of a global (with
26212     // an optional displacement) to be used with 'i'.
26213     GlobalAddressSDNode *GA = nullptr;
26214     int64_t Offset = 0;
26215
26216     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26217     while (1) {
26218       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26219         Offset += GA->getOffset();
26220         break;
26221       } else if (Op.getOpcode() == ISD::ADD) {
26222         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26223           Offset += C->getZExtValue();
26224           Op = Op.getOperand(0);
26225           continue;
26226         }
26227       } else if (Op.getOpcode() == ISD::SUB) {
26228         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26229           Offset += -C->getZExtValue();
26230           Op = Op.getOperand(0);
26231           continue;
26232         }
26233       }
26234
26235       // Otherwise, this isn't something we can handle, reject it.
26236       return;
26237     }
26238
26239     const GlobalValue *GV = GA->getGlobal();
26240     // If we require an extra load to get this address, as in PIC mode, we
26241     // can't accept it.
26242     if (isGlobalStubReference(
26243             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26244       return;
26245
26246     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26247                                         GA->getValueType(0), Offset);
26248     break;
26249   }
26250   }
26251
26252   if (Result.getNode()) {
26253     Ops.push_back(Result);
26254     return;
26255   }
26256   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26257 }
26258
26259 std::pair<unsigned, const TargetRegisterClass*>
26260 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
26261                                                 MVT VT) const {
26262   // First, see if this is a constraint that directly corresponds to an LLVM
26263   // register class.
26264   if (Constraint.size() == 1) {
26265     // GCC Constraint Letters
26266     switch (Constraint[0]) {
26267     default: break;
26268       // TODO: Slight differences here in allocation order and leaving
26269       // RIP in the class. Do they matter any more here than they do
26270       // in the normal allocation?
26271     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26272       if (Subtarget->is64Bit()) {
26273         if (VT == MVT::i32 || VT == MVT::f32)
26274           return std::make_pair(0U, &X86::GR32RegClass);
26275         if (VT == MVT::i16)
26276           return std::make_pair(0U, &X86::GR16RegClass);
26277         if (VT == MVT::i8 || VT == MVT::i1)
26278           return std::make_pair(0U, &X86::GR8RegClass);
26279         if (VT == MVT::i64 || VT == MVT::f64)
26280           return std::make_pair(0U, &X86::GR64RegClass);
26281         break;
26282       }
26283       // 32-bit fallthrough
26284     case 'Q':   // Q_REGS
26285       if (VT == MVT::i32 || VT == MVT::f32)
26286         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26287       if (VT == MVT::i16)
26288         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26289       if (VT == MVT::i8 || VT == MVT::i1)
26290         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26291       if (VT == MVT::i64)
26292         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26293       break;
26294     case 'r':   // GENERAL_REGS
26295     case 'l':   // INDEX_REGS
26296       if (VT == MVT::i8 || VT == MVT::i1)
26297         return std::make_pair(0U, &X86::GR8RegClass);
26298       if (VT == MVT::i16)
26299         return std::make_pair(0U, &X86::GR16RegClass);
26300       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26301         return std::make_pair(0U, &X86::GR32RegClass);
26302       return std::make_pair(0U, &X86::GR64RegClass);
26303     case 'R':   // LEGACY_REGS
26304       if (VT == MVT::i8 || VT == MVT::i1)
26305         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26306       if (VT == MVT::i16)
26307         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26308       if (VT == MVT::i32 || !Subtarget->is64Bit())
26309         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26310       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26311     case 'f':  // FP Stack registers.
26312       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26313       // value to the correct fpstack register class.
26314       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26315         return std::make_pair(0U, &X86::RFP32RegClass);
26316       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26317         return std::make_pair(0U, &X86::RFP64RegClass);
26318       return std::make_pair(0U, &X86::RFP80RegClass);
26319     case 'y':   // MMX_REGS if MMX allowed.
26320       if (!Subtarget->hasMMX()) break;
26321       return std::make_pair(0U, &X86::VR64RegClass);
26322     case 'Y':   // SSE_REGS if SSE2 allowed
26323       if (!Subtarget->hasSSE2()) break;
26324       // FALL THROUGH.
26325     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26326       if (!Subtarget->hasSSE1()) break;
26327
26328       switch (VT.SimpleTy) {
26329       default: break;
26330       // Scalar SSE types.
26331       case MVT::f32:
26332       case MVT::i32:
26333         return std::make_pair(0U, &X86::FR32RegClass);
26334       case MVT::f64:
26335       case MVT::i64:
26336         return std::make_pair(0U, &X86::FR64RegClass);
26337       // Vector types.
26338       case MVT::v16i8:
26339       case MVT::v8i16:
26340       case MVT::v4i32:
26341       case MVT::v2i64:
26342       case MVT::v4f32:
26343       case MVT::v2f64:
26344         return std::make_pair(0U, &X86::VR128RegClass);
26345       // AVX types.
26346       case MVT::v32i8:
26347       case MVT::v16i16:
26348       case MVT::v8i32:
26349       case MVT::v4i64:
26350       case MVT::v8f32:
26351       case MVT::v4f64:
26352         return std::make_pair(0U, &X86::VR256RegClass);
26353       case MVT::v8f64:
26354       case MVT::v16f32:
26355       case MVT::v16i32:
26356       case MVT::v8i64:
26357         return std::make_pair(0U, &X86::VR512RegClass);
26358       }
26359       break;
26360     }
26361   }
26362
26363   // Use the default implementation in TargetLowering to convert the register
26364   // constraint into a member of a register class.
26365   std::pair<unsigned, const TargetRegisterClass*> Res;
26366   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
26367
26368   // Not found as a standard register?
26369   if (!Res.second) {
26370     // Map st(0) -> st(7) -> ST0
26371     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26372         tolower(Constraint[1]) == 's' &&
26373         tolower(Constraint[2]) == 't' &&
26374         Constraint[3] == '(' &&
26375         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26376         Constraint[5] == ')' &&
26377         Constraint[6] == '}') {
26378
26379       Res.first = X86::FP0+Constraint[4]-'0';
26380       Res.second = &X86::RFP80RegClass;
26381       return Res;
26382     }
26383
26384     // GCC allows "st(0)" to be called just plain "st".
26385     if (StringRef("{st}").equals_lower(Constraint)) {
26386       Res.first = X86::FP0;
26387       Res.second = &X86::RFP80RegClass;
26388       return Res;
26389     }
26390
26391     // flags -> EFLAGS
26392     if (StringRef("{flags}").equals_lower(Constraint)) {
26393       Res.first = X86::EFLAGS;
26394       Res.second = &X86::CCRRegClass;
26395       return Res;
26396     }
26397
26398     // 'A' means EAX + EDX.
26399     if (Constraint == "A") {
26400       Res.first = X86::EAX;
26401       Res.second = &X86::GR32_ADRegClass;
26402       return Res;
26403     }
26404     return Res;
26405   }
26406
26407   // Otherwise, check to see if this is a register class of the wrong value
26408   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26409   // turn into {ax},{dx}.
26410   if (Res.second->hasType(VT))
26411     return Res;   // Correct type already, nothing to do.
26412
26413   // All of the single-register GCC register classes map their values onto
26414   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
26415   // really want an 8-bit or 32-bit register, map to the appropriate register
26416   // class and return the appropriate register.
26417   if (Res.second == &X86::GR16RegClass) {
26418     if (VT == MVT::i8 || VT == MVT::i1) {
26419       unsigned DestReg = 0;
26420       switch (Res.first) {
26421       default: break;
26422       case X86::AX: DestReg = X86::AL; break;
26423       case X86::DX: DestReg = X86::DL; break;
26424       case X86::CX: DestReg = X86::CL; break;
26425       case X86::BX: DestReg = X86::BL; break;
26426       }
26427       if (DestReg) {
26428         Res.first = DestReg;
26429         Res.second = &X86::GR8RegClass;
26430       }
26431     } else if (VT == MVT::i32 || VT == MVT::f32) {
26432       unsigned DestReg = 0;
26433       switch (Res.first) {
26434       default: break;
26435       case X86::AX: DestReg = X86::EAX; break;
26436       case X86::DX: DestReg = X86::EDX; break;
26437       case X86::CX: DestReg = X86::ECX; break;
26438       case X86::BX: DestReg = X86::EBX; break;
26439       case X86::SI: DestReg = X86::ESI; break;
26440       case X86::DI: DestReg = X86::EDI; break;
26441       case X86::BP: DestReg = X86::EBP; break;
26442       case X86::SP: DestReg = X86::ESP; break;
26443       }
26444       if (DestReg) {
26445         Res.first = DestReg;
26446         Res.second = &X86::GR32RegClass;
26447       }
26448     } else if (VT == MVT::i64 || VT == MVT::f64) {
26449       unsigned DestReg = 0;
26450       switch (Res.first) {
26451       default: break;
26452       case X86::AX: DestReg = X86::RAX; break;
26453       case X86::DX: DestReg = X86::RDX; break;
26454       case X86::CX: DestReg = X86::RCX; break;
26455       case X86::BX: DestReg = X86::RBX; break;
26456       case X86::SI: DestReg = X86::RSI; break;
26457       case X86::DI: DestReg = X86::RDI; break;
26458       case X86::BP: DestReg = X86::RBP; break;
26459       case X86::SP: DestReg = X86::RSP; break;
26460       }
26461       if (DestReg) {
26462         Res.first = DestReg;
26463         Res.second = &X86::GR64RegClass;
26464       }
26465     }
26466   } else if (Res.second == &X86::FR32RegClass ||
26467              Res.second == &X86::FR64RegClass ||
26468              Res.second == &X86::VR128RegClass ||
26469              Res.second == &X86::VR256RegClass ||
26470              Res.second == &X86::FR32XRegClass ||
26471              Res.second == &X86::FR64XRegClass ||
26472              Res.second == &X86::VR128XRegClass ||
26473              Res.second == &X86::VR256XRegClass ||
26474              Res.second == &X86::VR512RegClass) {
26475     // Handle references to XMM physical registers that got mapped into the
26476     // wrong class.  This can happen with constraints like {xmm0} where the
26477     // target independent register mapper will just pick the first match it can
26478     // find, ignoring the required type.
26479
26480     if (VT == MVT::f32 || VT == MVT::i32)
26481       Res.second = &X86::FR32RegClass;
26482     else if (VT == MVT::f64 || VT == MVT::i64)
26483       Res.second = &X86::FR64RegClass;
26484     else if (X86::VR128RegClass.hasType(VT))
26485       Res.second = &X86::VR128RegClass;
26486     else if (X86::VR256RegClass.hasType(VT))
26487       Res.second = &X86::VR256RegClass;
26488     else if (X86::VR512RegClass.hasType(VT))
26489       Res.second = &X86::VR512RegClass;
26490   }
26491
26492   return Res;
26493 }
26494
26495 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
26496                                             Type *Ty) const {
26497   // Scaling factors are not free at all.
26498   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26499   // will take 2 allocations in the out of order engine instead of 1
26500   // for plain addressing mode, i.e. inst (reg1).
26501   // E.g.,
26502   // vaddps (%rsi,%drx), %ymm0, %ymm1
26503   // Requires two allocations (one for the load, one for the computation)
26504   // whereas:
26505   // vaddps (%rsi), %ymm0, %ymm1
26506   // Requires just 1 allocation, i.e., freeing allocations for other operations
26507   // and having less micro operations to execute.
26508   //
26509   // For some X86 architectures, this is even worse because for instance for
26510   // stores, the complex addressing mode forces the instruction to use the
26511   // "load" ports instead of the dedicated "store" port.
26512   // E.g., on Haswell:
26513   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26514   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26515   if (isLegalAddressingMode(AM, Ty))
26516     // Scale represents reg2 * scale, thus account for 1
26517     // as soon as we use a second register.
26518     return AM.Scale != 0;
26519   return -1;
26520 }
26521
26522 bool X86TargetLowering::isTargetFTOL() const {
26523   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26524 }