5c862b5f62121b3bf1bd32ce4d3aeab640c97677
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/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<int> ReciprocalEstimateRefinementSteps(
70     "x86-recip-refinement-steps", cl::init(1),
71     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
72              "result of the hardware reciprocal estimate instruction."),
73     cl::NotHidden);
74
75 // Forward declarations.
76 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
77                        SDValue V2);
78
79 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
80                                 SelectionDAG &DAG, SDLoc dl,
81                                 unsigned vectorWidth) {
82   assert((vectorWidth == 128 || vectorWidth == 256) &&
83          "Unsupported vector width");
84   EVT VT = Vec.getValueType();
85   EVT ElVT = VT.getVectorElementType();
86   unsigned Factor = VT.getSizeInBits()/vectorWidth;
87   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88                                   VT.getVectorNumElements()/Factor);
89
90   // Extract from UNDEF is UNDEF.
91   if (Vec.getOpcode() == ISD::UNDEF)
92     return DAG.getUNDEF(ResultVT);
93
94   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
95   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
96
97   // This is the index of the first element of the vectorWidth-bit chunk
98   // we want.
99   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
100                                * ElemsPerChunk);
101
102   // If the input is a buildvector just emit a smaller one.
103   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
104     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
105                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
106                                     ElemsPerChunk));
107
108   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
109   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
110 }
111
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
154 }
155
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
163                                   SelectionDAG &DAG,SDLoc dl) {
164   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
165   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
166 }
167
168 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
169                                   SelectionDAG &DAG, SDLoc dl) {
170   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
171   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
172 }
173
174 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
175 /// instructions. This is used because creating CONCAT_VECTOR nodes of
176 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
177 /// large BUILD_VECTORS.
178 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
179                                    unsigned NumElems, SelectionDAG &DAG,
180                                    SDLoc dl) {
181   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
182   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
183 }
184
185 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
186                                    unsigned NumElems, SelectionDAG &DAG,
187                                    SDLoc dl) {
188   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
189   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
190 }
191
192 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
193                                      const X86Subtarget &STI)
194     : TargetLowering(TM), Subtarget(&STI) {
195   X86ScalarSSEf64 = Subtarget->hasSSE2();
196   X86ScalarSSEf32 = Subtarget->hasSSE1();
197   TD = getDataLayout();
198
199   // Set up the TargetLowering object.
200   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
201
202   // X86 is weird. It always uses i8 for shift amounts and setcc results.
203   setBooleanContents(ZeroOrOneBooleanContent);
204   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
205   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
206
207   // For 64-bit, since we have so many registers, use the ILP scheduler.
208   // For 32-bit, use the register pressure specific scheduling.
209   // For Atom, always use ILP scheduling.
210   if (Subtarget->isAtom())
211     setSchedulingPreference(Sched::ILP);
212   else if (Subtarget->is64Bit())
213     setSchedulingPreference(Sched::ILP);
214   else
215     setSchedulingPreference(Sched::RegPressure);
216   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
217   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
218
219   // Bypass expensive divides on Atom when compiling with O2.
220   if (TM.getOptLevel() >= CodeGenOpt::Default) {
221     if (Subtarget->hasSlowDivide32())
222       addBypassSlowDiv(32, 8);
223     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
224       addBypassSlowDiv(64, 16);
225   }
226
227   if (Subtarget->isTargetKnownWindowsMSVC()) {
228     // Setup Windows compiler runtime calls.
229     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
230     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
231     setLibcallName(RTLIB::SREM_I64, "_allrem");
232     setLibcallName(RTLIB::UREM_I64, "_aullrem");
233     setLibcallName(RTLIB::MUL_I64, "_allmul");
234     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
235     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
236     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
237     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
238     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
239
240     // The _ftol2 runtime function has an unusual calling conv, which
241     // is modeled by a special pseudo-instruction.
242     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
243     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
244     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
245     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
246   }
247
248   if (Subtarget->isTargetDarwin()) {
249     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
250     setUseUnderscoreSetJmp(false);
251     setUseUnderscoreLongJmp(false);
252   } else if (Subtarget->isTargetWindowsGNU()) {
253     // MS runtime is weird: it exports _setjmp, but longjmp!
254     setUseUnderscoreSetJmp(true);
255     setUseUnderscoreLongJmp(false);
256   } else {
257     setUseUnderscoreSetJmp(true);
258     setUseUnderscoreLongJmp(true);
259   }
260
261   // Set up the register classes.
262   addRegisterClass(MVT::i8, &X86::GR8RegClass);
263   addRegisterClass(MVT::i16, &X86::GR16RegClass);
264   addRegisterClass(MVT::i32, &X86::GR32RegClass);
265   if (Subtarget->is64Bit())
266     addRegisterClass(MVT::i64, &X86::GR64RegClass);
267
268   for (MVT VT : MVT::integer_valuetypes())
269     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
270
271   // We don't accept any truncstore of integer registers.
272   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
273   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
274   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
275   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
276   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
277   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
278
279   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
280
281   // SETOEQ and SETUNE require checking two conditions.
282   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
283   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
284   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
285   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
286   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
287   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
288
289   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
290   // operation.
291   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
292   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
293   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
294
295   if (Subtarget->is64Bit()) {
296     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
297     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
298   } else if (!TM.Options.UseSoftFloat) {
299     // We have an algorithm for SSE2->double, and we turn this into a
300     // 64-bit FILD followed by conditional FADD for other targets.
301     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
302     // We have an algorithm for SSE2, and we turn this into a 64-bit
303     // FILD for other targets.
304     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
305   }
306
307   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
308   // this operation.
309   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
310   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
311
312   if (!TM.Options.UseSoftFloat) {
313     // SSE has no i16 to fp conversion, only i32
314     if (X86ScalarSSEf32) {
315       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
316       // f32 and f64 cases are Legal, f80 case is not
317       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
318     } else {
319       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
320       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
321     }
322   } else {
323     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
324     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
325   }
326
327   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
328   // are Legal, f80 is custom lowered.
329   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
330   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
331
332   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
333   // this operation.
334   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
335   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
336
337   if (X86ScalarSSEf32) {
338     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
339     // f32 and f64 cases are Legal, f80 case is not
340     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
341   } else {
342     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
343     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
344   }
345
346   // Handle FP_TO_UINT by promoting the destination to a larger signed
347   // conversion.
348   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
349   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
350   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
351
352   if (Subtarget->is64Bit()) {
353     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
354     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
355   } else if (!TM.Options.UseSoftFloat) {
356     // Since AVX is a superset of SSE3, only check for SSE here.
357     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
358       // Expand FP_TO_UINT into a select.
359       // FIXME: We would like to use a Custom expander here eventually to do
360       // the optimal thing for SSE vs. the default expansion in the legalizer.
361       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
362     else
363       // With SSE3 we can use fisttpll to convert to a signed i64; without
364       // SSE, we're stuck with a fistpll.
365       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
366   }
367
368   if (isTargetFTOL()) {
369     // Use the _ftol2 runtime function, which has a pseudo-instruction
370     // to handle its weird calling convention.
371     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
372   }
373
374   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
375   if (!X86ScalarSSEf64) {
376     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
377     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
378     if (Subtarget->is64Bit()) {
379       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
380       // Without SSE, i64->f64 goes through memory.
381       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
382     }
383   }
384
385   // Scalar integer divide and remainder are lowered to use operations that
386   // produce two results, to match the available instructions. This exposes
387   // the two-result form to trivial CSE, which is able to combine x/y and x%y
388   // into a single instruction.
389   //
390   // Scalar integer multiply-high is also lowered to use two-result
391   // operations, to match the available instructions. However, plain multiply
392   // (low) operations are left as Legal, as there are single-result
393   // instructions for this in x86. Using the two-result multiply instructions
394   // when both high and low results are needed must be arranged by dagcombine.
395   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
396     MVT VT = IntVTs[i];
397     setOperationAction(ISD::MULHS, VT, Expand);
398     setOperationAction(ISD::MULHU, VT, Expand);
399     setOperationAction(ISD::SDIV, VT, Expand);
400     setOperationAction(ISD::UDIV, VT, Expand);
401     setOperationAction(ISD::SREM, VT, Expand);
402     setOperationAction(ISD::UREM, VT, Expand);
403
404     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
405     setOperationAction(ISD::ADDC, VT, Custom);
406     setOperationAction(ISD::ADDE, VT, Custom);
407     setOperationAction(ISD::SUBC, VT, Custom);
408     setOperationAction(ISD::SUBE, VT, Custom);
409   }
410
411   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
412   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
413   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
414   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
415   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
416   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
417   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
418   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
419   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
420   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
421   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
422   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
423   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
424   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
425   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
426   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
427   if (Subtarget->is64Bit())
428     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
429   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
430   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
431   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
432   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
433   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
434   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
435   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
436   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
437
438   // Promote the i8 variants and force them on up to i32 which has a shorter
439   // encoding.
440   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
441   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
442   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
443   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
444   if (Subtarget->hasBMI()) {
445     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
446     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
447     if (Subtarget->is64Bit())
448       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
449   } else {
450     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
451     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
452     if (Subtarget->is64Bit())
453       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
454   }
455
456   if (Subtarget->hasLZCNT()) {
457     // When promoting the i8 variants, force them to i32 for a shorter
458     // encoding.
459     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
460     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
461     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
462     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
463     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
464     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
465     if (Subtarget->is64Bit())
466       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
467   } else {
468     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
469     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
470     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
471     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
472     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
473     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
474     if (Subtarget->is64Bit()) {
475       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
476       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
477     }
478   }
479
480   // Special handling for half-precision floating point conversions.
481   // If we don't have F16C support, then lower half float conversions
482   // into library calls.
483   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
484     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
485     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
486   }
487
488   // There's never any support for operations beyond MVT::f32.
489   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
490   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
491   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
492   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
493
494   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
495   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
496   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
497   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
498   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
499   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
500
501   if (Subtarget->hasPOPCNT()) {
502     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
503   } else {
504     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
505     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
506     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
507     if (Subtarget->is64Bit())
508       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
509   }
510
511   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
512
513   if (!Subtarget->hasMOVBE())
514     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
515
516   // These should be promoted to a larger select which is supported.
517   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
518   // X86 wants to expand cmov itself.
519   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
520   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
522   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
523   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
524   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
526   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
528   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
529   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
530   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
531   if (Subtarget->is64Bit()) {
532     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
533     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
534   }
535   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
536   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
537   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
538   // support continuation, user-level threading, and etc.. As a result, no
539   // other SjLj exception interfaces are implemented and please don't build
540   // your own exception handling based on them.
541   // LLVM/Clang supports zero-cost DWARF exception handling.
542   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
543   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
544
545   // Darwin ABI issue.
546   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
547   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
548   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
549   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
550   if (Subtarget->is64Bit())
551     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
552   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
553   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
554   if (Subtarget->is64Bit()) {
555     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
556     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
557     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
558     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
559     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
560   }
561   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
562   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
563   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
564   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
565   if (Subtarget->is64Bit()) {
566     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
567     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
568     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
569   }
570
571   if (Subtarget->hasSSE1())
572     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
573
574   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
575
576   // Expand certain atomics
577   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
578     MVT VT = IntVTs[i];
579     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
581     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
582   }
583
584   if (Subtarget->hasCmpxchg16b()) {
585     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
586   }
587
588   // FIXME - use subtarget debug flags
589   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
590       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
591     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
592   }
593
594   if (Subtarget->is64Bit()) {
595     setExceptionPointerRegister(X86::RAX);
596     setExceptionSelectorRegister(X86::RDX);
597   } else {
598     setExceptionPointerRegister(X86::EAX);
599     setExceptionSelectorRegister(X86::EDX);
600   }
601   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
602   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
603
604   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
605   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
606
607   setOperationAction(ISD::TRAP, MVT::Other, Legal);
608   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
609
610   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
611   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
612   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
613   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
614     // TargetInfo::X86_64ABIBuiltinVaList
615     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
616     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
617   } else {
618     // TargetInfo::CharPtrBuiltinVaList
619     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
620     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
621   }
622
623   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
624   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
625
626   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
627
628   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
629     // f32 and f64 use SSE.
630     // Set up the FP register classes.
631     addRegisterClass(MVT::f32, &X86::FR32RegClass);
632     addRegisterClass(MVT::f64, &X86::FR64RegClass);
633
634     // Use ANDPD to simulate FABS.
635     setOperationAction(ISD::FABS , MVT::f64, Custom);
636     setOperationAction(ISD::FABS , MVT::f32, Custom);
637
638     // Use XORP to simulate FNEG.
639     setOperationAction(ISD::FNEG , MVT::f64, Custom);
640     setOperationAction(ISD::FNEG , MVT::f32, Custom);
641
642     // Use ANDPD and ORPD to simulate FCOPYSIGN.
643     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
644     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
645
646     // Lower this to FGETSIGNx86 plus an AND.
647     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
648     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
649
650     // We don't support sin/cos/fmod
651     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
652     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
653     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
654     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
655     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
656     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
657
658     // Expand FP immediates into loads from the stack, except for the special
659     // cases we handle.
660     addLegalFPImmediate(APFloat(+0.0)); // xorpd
661     addLegalFPImmediate(APFloat(+0.0f)); // xorps
662   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
663     // Use SSE for f32, x87 for f64.
664     // Set up the FP register classes.
665     addRegisterClass(MVT::f32, &X86::FR32RegClass);
666     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
667
668     // Use ANDPS to simulate FABS.
669     setOperationAction(ISD::FABS , MVT::f32, Custom);
670
671     // Use XORP to simulate FNEG.
672     setOperationAction(ISD::FNEG , MVT::f32, Custom);
673
674     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
675
676     // Use ANDPS and ORPS to simulate FCOPYSIGN.
677     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
678     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
679
680     // We don't support sin/cos/fmod
681     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
682     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
683     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
684
685     // Special cases we handle for FP constants.
686     addLegalFPImmediate(APFloat(+0.0f)); // xorps
687     addLegalFPImmediate(APFloat(+0.0)); // FLD0
688     addLegalFPImmediate(APFloat(+1.0)); // FLD1
689     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
690     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
691
692     if (!TM.Options.UnsafeFPMath) {
693       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
694       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
695       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
696     }
697   } else if (!TM.Options.UseSoftFloat) {
698     // f32 and f64 in x87.
699     // Set up the FP register classes.
700     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
701     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
702
703     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
704     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
705     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
706     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
707
708     if (!TM.Options.UnsafeFPMath) {
709       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
710       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
711       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
712       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
713       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
714       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
715     }
716     addLegalFPImmediate(APFloat(+0.0)); // FLD0
717     addLegalFPImmediate(APFloat(+1.0)); // FLD1
718     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
719     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
720     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
721     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
722     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
723     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
724   }
725
726   // We don't support FMA.
727   setOperationAction(ISD::FMA, MVT::f64, Expand);
728   setOperationAction(ISD::FMA, MVT::f32, Expand);
729
730   // Long double always uses X87.
731   if (!TM.Options.UseSoftFloat) {
732     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
733     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
734     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
735     {
736       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
737       addLegalFPImmediate(TmpFlt);  // FLD0
738       TmpFlt.changeSign();
739       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
740
741       bool ignored;
742       APFloat TmpFlt2(+1.0);
743       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
744                       &ignored);
745       addLegalFPImmediate(TmpFlt2);  // FLD1
746       TmpFlt2.changeSign();
747       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
748     }
749
750     if (!TM.Options.UnsafeFPMath) {
751       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
752       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
753       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
754     }
755
756     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
757     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
758     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
759     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
760     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
761     setOperationAction(ISD::FMA, MVT::f80, Expand);
762   }
763
764   // Always use a library call for pow.
765   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
766   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
767   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
768
769   setOperationAction(ISD::FLOG, MVT::f80, Expand);
770   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
771   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
772   setOperationAction(ISD::FEXP, MVT::f80, Expand);
773   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
774   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
775   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
776
777   // First set operation action for all vector types to either promote
778   // (for widening) or expand (for scalarization). Then we will selectively
779   // turn on ones that can be effectively codegen'd.
780   for (MVT VT : MVT::vector_valuetypes()) {
781     setOperationAction(ISD::ADD , VT, Expand);
782     setOperationAction(ISD::SUB , VT, Expand);
783     setOperationAction(ISD::FADD, VT, Expand);
784     setOperationAction(ISD::FNEG, VT, Expand);
785     setOperationAction(ISD::FSUB, VT, Expand);
786     setOperationAction(ISD::MUL , VT, Expand);
787     setOperationAction(ISD::FMUL, VT, Expand);
788     setOperationAction(ISD::SDIV, VT, Expand);
789     setOperationAction(ISD::UDIV, VT, Expand);
790     setOperationAction(ISD::FDIV, VT, Expand);
791     setOperationAction(ISD::SREM, VT, Expand);
792     setOperationAction(ISD::UREM, VT, Expand);
793     setOperationAction(ISD::LOAD, VT, Expand);
794     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
796     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
797     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
798     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
799     setOperationAction(ISD::FABS, VT, Expand);
800     setOperationAction(ISD::FSIN, VT, Expand);
801     setOperationAction(ISD::FSINCOS, VT, Expand);
802     setOperationAction(ISD::FCOS, VT, Expand);
803     setOperationAction(ISD::FSINCOS, VT, Expand);
804     setOperationAction(ISD::FREM, VT, Expand);
805     setOperationAction(ISD::FMA,  VT, Expand);
806     setOperationAction(ISD::FPOWI, VT, Expand);
807     setOperationAction(ISD::FSQRT, VT, Expand);
808     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
809     setOperationAction(ISD::FFLOOR, VT, Expand);
810     setOperationAction(ISD::FCEIL, VT, Expand);
811     setOperationAction(ISD::FTRUNC, VT, Expand);
812     setOperationAction(ISD::FRINT, VT, Expand);
813     setOperationAction(ISD::FNEARBYINT, VT, Expand);
814     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
815     setOperationAction(ISD::MULHS, VT, Expand);
816     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
817     setOperationAction(ISD::MULHU, VT, Expand);
818     setOperationAction(ISD::SDIVREM, VT, Expand);
819     setOperationAction(ISD::UDIVREM, VT, Expand);
820     setOperationAction(ISD::FPOW, VT, Expand);
821     setOperationAction(ISD::CTPOP, VT, Expand);
822     setOperationAction(ISD::CTTZ, VT, Expand);
823     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
824     setOperationAction(ISD::CTLZ, VT, Expand);
825     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
826     setOperationAction(ISD::SHL, VT, Expand);
827     setOperationAction(ISD::SRA, VT, Expand);
828     setOperationAction(ISD::SRL, VT, Expand);
829     setOperationAction(ISD::ROTL, VT, Expand);
830     setOperationAction(ISD::ROTR, VT, Expand);
831     setOperationAction(ISD::BSWAP, VT, Expand);
832     setOperationAction(ISD::SETCC, VT, Expand);
833     setOperationAction(ISD::FLOG, VT, Expand);
834     setOperationAction(ISD::FLOG2, VT, Expand);
835     setOperationAction(ISD::FLOG10, VT, Expand);
836     setOperationAction(ISD::FEXP, VT, Expand);
837     setOperationAction(ISD::FEXP2, VT, Expand);
838     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
839     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
840     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
841     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
842     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
843     setOperationAction(ISD::TRUNCATE, VT, Expand);
844     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
845     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
846     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
847     setOperationAction(ISD::VSELECT, VT, Expand);
848     setOperationAction(ISD::SELECT_CC, VT, Expand);
849     for (MVT InnerVT : MVT::vector_valuetypes()) {
850       setTruncStoreAction(InnerVT, VT, Expand);
851
852       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
853       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
854
855       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
856       // types, we have to deal with them whether we ask for Expansion or not.
857       // Setting Expand causes its own optimisation problems though, so leave
858       // them legal.
859       if (VT.getVectorElementType() == MVT::i1)
860         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
861     }
862   }
863
864   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
865   // with -msoft-float, disable use of MMX as well.
866   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
867     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
868     // No operations on x86mmx supported, everything uses intrinsics.
869   }
870
871   // MMX-sized vectors (other than x86mmx) are expected to be expanded
872   // into smaller operations.
873   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
874     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
875     setOperationAction(ISD::AND,                MMXTy,      Expand);
876     setOperationAction(ISD::OR,                 MMXTy,      Expand);
877     setOperationAction(ISD::XOR,                MMXTy,      Expand);
878     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
879     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
880     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
881   }
882   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
883
884   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
885     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
886
887     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
888     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
889     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
890     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
891     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
892     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
893     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
894     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
895     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
897     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
898     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
899     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
900     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
901   }
902
903   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
904     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
905
906     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
907     // registers cannot be used even for integer operations.
908     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
909     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
910     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
911     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
912
913     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
914     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
915     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
916     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
917     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
918     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
919     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
920     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
921     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
922     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
923     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
924     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
925     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
926     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
927     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
928     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
929     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
930     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
931     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
932     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
933     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
934     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
935
936     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
937     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
938     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
939     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
940
941     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
942     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
943     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
944     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
945     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
946
947     // Only provide customized ctpop vector bit twiddling for vector types we
948     // know to perform better than using the popcnt instructions on each vector
949     // element. If popcnt isn't supported, always provide the custom version.
950     if (!Subtarget->hasPOPCNT()) {
951       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
952       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
953     }
954
955     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
956     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
957       MVT VT = (MVT::SimpleValueType)i;
958       // Do not attempt to custom lower non-power-of-2 vectors
959       if (!isPowerOf2_32(VT.getVectorNumElements()))
960         continue;
961       // Do not attempt to custom lower non-128-bit vectors
962       if (!VT.is128BitVector())
963         continue;
964       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
965       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
966       setOperationAction(ISD::VSELECT,            VT, Custom);
967       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
968     }
969
970     // We support custom legalizing of sext and anyext loads for specific
971     // memory vector types which we can load as a scalar (or sequence of
972     // scalars) and extend in-register to a legal 128-bit vector type. For sext
973     // loads these must work with a single scalar load.
974     for (MVT VT : MVT::integer_vector_valuetypes()) {
975       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
976       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
977       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
978       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
979       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
980       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
981       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
982       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
983       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
984     }
985
986     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
987     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
988     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
989     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
990     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
991     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
992     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
994
995     if (Subtarget->is64Bit()) {
996       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
997       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
998     }
999
1000     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003
1004       // Do not attempt to promote non-128-bit vectors
1005       if (!VT.is128BitVector())
1006         continue;
1007
1008       setOperationAction(ISD::AND,    VT, Promote);
1009       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1010       setOperationAction(ISD::OR,     VT, Promote);
1011       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1012       setOperationAction(ISD::XOR,    VT, Promote);
1013       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1014       setOperationAction(ISD::LOAD,   VT, Promote);
1015       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1016       setOperationAction(ISD::SELECT, VT, Promote);
1017       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1018     }
1019
1020     // Custom lower v2i64 and v2f64 selects.
1021     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1022     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1023     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1024     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1025
1026     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1027     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1028
1029     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1030     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1031     // As there is no 64-bit GPR available, we need build a special custom
1032     // sequence to convert from v2i32 to v2f32.
1033     if (!Subtarget->is64Bit())
1034       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1035
1036     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1037     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1038
1039     for (MVT VT : MVT::fp_vector_valuetypes())
1040       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1041
1042     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1043     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1044     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1045   }
1046
1047   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1048     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1049       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
1050       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
1051       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
1052       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
1053       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
1054     }
1055
1056     // FIXME: Do we need to handle scalar-to-vector here?
1057     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1058
1059     // We directly match byte blends in the backend as they match the VSELECT
1060     // condition form.
1061     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1062
1063     // SSE41 brings specific instructions for doing vector sign extend even in
1064     // cases where we don't have SRA.
1065     for (MVT VT : MVT::integer_vector_valuetypes()) {
1066       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1067       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1068       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1069     }
1070
1071     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1072     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1073     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1074     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1075     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1076     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1077     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1078
1079     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1080     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1081     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1082     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1083     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1084     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1085
1086     // i8 and i16 vectors are custom because the source register and source
1087     // source memory operand types are not the same width.  f32 vectors are
1088     // custom since the immediate controlling the insert encodes additional
1089     // information.
1090     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1091     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1092     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1093     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1094
1095     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1096     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1097     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1098     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1099
1100     // FIXME: these should be Legal, but that's only for the case where
1101     // the index is constant.  For now custom expand to deal with that.
1102     if (Subtarget->is64Bit()) {
1103       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1104       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1105     }
1106   }
1107
1108   if (Subtarget->hasSSE2()) {
1109     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1110     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1111
1112     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1113     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1114
1115     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1116     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1117
1118     // In the customized shift lowering, the legal cases in AVX2 will be
1119     // recognized.
1120     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1121     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1122
1123     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1124     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1125
1126     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1127   }
1128
1129   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1130     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1131     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1132     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1133     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1134     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1135     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1136
1137     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1138     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1139     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1140
1141     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1142     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1143     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1144     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1145     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1146     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1147     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1148     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1149     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1150     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1151     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1152     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1153
1154     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1155     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1156     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1157     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1158     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1159     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1160     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1161     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1162     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1163     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1164     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1165     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1166
1167     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1168     // even though v8i16 is a legal type.
1169     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1170     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1171     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1172
1173     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1174     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1175     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1176
1177     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1178     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1179
1180     for (MVT VT : MVT::fp_vector_valuetypes())
1181       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1182
1183     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1184     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1185
1186     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1187     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1188
1189     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1190     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1191
1192     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1193     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1194     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1195     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1196
1197     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1198     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1199     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1200
1201     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1202     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1203     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1204     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1205     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1206     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1207     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1208     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1209     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1210     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1211     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1212     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1213
1214     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1215       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1216       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1217       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1218       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1219       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1220       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1221     }
1222
1223     if (Subtarget->hasInt256()) {
1224       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1225       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1226       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1227       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1228
1229       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1230       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1231       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1232       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1233
1234       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1235       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1236       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1237       // Don't lower v32i8 because there is no 128-bit byte mul
1238
1239       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1240       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1241       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1242       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1243
1244       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1245       // when we have a 256bit-wide blend with immediate.
1246       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1247
1248       // Only provide customized ctpop vector bit twiddling for vector types we
1249       // know to perform better than using the popcnt instructions on each
1250       // vector element. If popcnt isn't supported, always provide the custom
1251       // version.
1252       if (!Subtarget->hasPOPCNT())
1253         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1254
1255       // Custom CTPOP always performs better on natively supported v8i32
1256       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1257
1258       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1259       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1260       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1261       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1262       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1263       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1264       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1265
1266       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1267       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1268       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1269       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1270       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1271       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1272     } else {
1273       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1274       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1275       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1276       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1277
1278       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1279       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1280       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1281       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1282
1283       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1284       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1285       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1286       // Don't lower v32i8 because there is no 128-bit byte mul
1287     }
1288
1289     // In the customized shift lowering, the legal cases in AVX2 will be
1290     // recognized.
1291     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1292     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1293
1294     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1295     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1296
1297     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1298
1299     // Custom lower several nodes for 256-bit types.
1300     for (MVT VT : MVT::vector_valuetypes()) {
1301       if (VT.getScalarSizeInBits() >= 32) {
1302         setOperationAction(ISD::MLOAD,  VT, Legal);
1303         setOperationAction(ISD::MSTORE, VT, Legal);
1304       }
1305       // Extract subvector is special because the value type
1306       // (result) is 128-bit but the source is 256-bit wide.
1307       if (VT.is128BitVector()) {
1308         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1309       }
1310       // Do not attempt to custom lower other non-256-bit vectors
1311       if (!VT.is256BitVector())
1312         continue;
1313
1314       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1315       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1316       setOperationAction(ISD::VSELECT,            VT, Custom);
1317       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1318       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1319       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1320       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1321       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1322     }
1323
1324     if (Subtarget->hasInt256())
1325       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1326
1327
1328     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1329     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1330       MVT VT = (MVT::SimpleValueType)i;
1331
1332       // Do not attempt to promote non-256-bit vectors
1333       if (!VT.is256BitVector())
1334         continue;
1335
1336       setOperationAction(ISD::AND,    VT, Promote);
1337       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1338       setOperationAction(ISD::OR,     VT, Promote);
1339       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1340       setOperationAction(ISD::XOR,    VT, Promote);
1341       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1342       setOperationAction(ISD::LOAD,   VT, Promote);
1343       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1344       setOperationAction(ISD::SELECT, VT, Promote);
1345       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1346     }
1347   }
1348
1349   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1350     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1351     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1352     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1353     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1354
1355     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1356     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1357     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1358
1359     for (MVT VT : MVT::fp_vector_valuetypes())
1360       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1361
1362     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1363     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1364     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1365     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1366     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1367     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1368     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1369     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1370     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1371     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1372
1373     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1374     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1375     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1376     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1377     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1378     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1379
1380     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1381     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1382     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1383     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1384     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1385     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1386     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1387     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1388
1389     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1390     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1391     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1392     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1393     if (Subtarget->is64Bit()) {
1394       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1395       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1396       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1397       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1398     }
1399     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1400     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1401     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1402     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1403     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1404     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1405     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1406     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1407     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1408     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1409     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1410     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1411     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1412     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1413
1414     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1415     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1416     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1417     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1418     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1419     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1420     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1421     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1422     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1423     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1424     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1425     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1426     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1427
1428     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1429     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1430     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1431     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1432     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1433     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1434     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1435     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1436     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1437     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1438
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1444
1445     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1446     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1447
1448     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1449
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1459
1460     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1461     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1462
1463     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1469     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1470
1471     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1479     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1483
1484     if (Subtarget->hasCDI()) {
1485       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1486       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1487     }
1488
1489     // Custom lower several nodes.
1490     for (MVT VT : MVT::vector_valuetypes()) {
1491       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1492       // Extract subvector is special because the value type
1493       // (result) is 256/128-bit but the source is 512-bit wide.
1494       if (VT.is128BitVector() || VT.is256BitVector()) {
1495         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1496       }
1497       if (VT.getVectorElementType() == MVT::i1)
1498         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1499
1500       // Do not attempt to custom lower other non-512-bit vectors
1501       if (!VT.is512BitVector())
1502         continue;
1503
1504       if ( EltSize >= 32) {
1505         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1506         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1507         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1508         setOperationAction(ISD::VSELECT,             VT, Legal);
1509         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1510         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1511         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1512         setOperationAction(ISD::MLOAD,               VT, Legal);
1513         setOperationAction(ISD::MSTORE,              VT, Legal);
1514       }
1515     }
1516     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1517       MVT VT = (MVT::SimpleValueType)i;
1518
1519       // Do not attempt to promote non-512-bit vectors.
1520       if (!VT.is512BitVector())
1521         continue;
1522
1523       setOperationAction(ISD::SELECT, VT, Promote);
1524       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1525     }
1526   }// has  AVX-512
1527
1528   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1529     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1530     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1531
1532     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1533     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1534
1535     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1536     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1537     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1538     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1539     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1540     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1541     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1542     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1543     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1544     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1545     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1546     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1547     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1548
1549     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1550       const MVT VT = (MVT::SimpleValueType)i;
1551
1552       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1553
1554       // Do not attempt to promote non-512-bit vectors.
1555       if (!VT.is512BitVector())
1556         continue;
1557
1558       if (EltSize < 32) {
1559         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1560         setOperationAction(ISD::VSELECT,             VT, Legal);
1561       }
1562     }
1563   }
1564
1565   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1566     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1567     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1568
1569     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1570     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1571     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1572     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1573     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1574     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1575
1576     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1577     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1578     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1579     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1580     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1581     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1582   }
1583
1584   // We want to custom lower some of our intrinsics.
1585   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1586   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1587   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1588   if (!Subtarget->is64Bit())
1589     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1590
1591   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1592   // handle type legalization for these operations here.
1593   //
1594   // FIXME: We really should do custom legalization for addition and
1595   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1596   // than generic legalization for 64-bit multiplication-with-overflow, though.
1597   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1598     // Add/Sub/Mul with overflow operations are custom lowered.
1599     MVT VT = IntVTs[i];
1600     setOperationAction(ISD::SADDO, VT, Custom);
1601     setOperationAction(ISD::UADDO, VT, Custom);
1602     setOperationAction(ISD::SSUBO, VT, Custom);
1603     setOperationAction(ISD::USUBO, VT, Custom);
1604     setOperationAction(ISD::SMULO, VT, Custom);
1605     setOperationAction(ISD::UMULO, VT, Custom);
1606   }
1607
1608
1609   if (!Subtarget->is64Bit()) {
1610     // These libcalls are not available in 32-bit.
1611     setLibcallName(RTLIB::SHL_I128, nullptr);
1612     setLibcallName(RTLIB::SRL_I128, nullptr);
1613     setLibcallName(RTLIB::SRA_I128, nullptr);
1614   }
1615
1616   // Combine sin / cos into one node or libcall if possible.
1617   if (Subtarget->hasSinCos()) {
1618     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1619     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1620     if (Subtarget->isTargetDarwin()) {
1621       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1622       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1623       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1624       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1625     }
1626   }
1627
1628   if (Subtarget->isTargetWin64()) {
1629     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1630     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1631     setOperationAction(ISD::SREM, MVT::i128, Custom);
1632     setOperationAction(ISD::UREM, MVT::i128, Custom);
1633     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1634     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1635   }
1636
1637   // We have target-specific dag combine patterns for the following nodes:
1638   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1639   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1640   setTargetDAGCombine(ISD::BITCAST);
1641   setTargetDAGCombine(ISD::VSELECT);
1642   setTargetDAGCombine(ISD::SELECT);
1643   setTargetDAGCombine(ISD::SHL);
1644   setTargetDAGCombine(ISD::SRA);
1645   setTargetDAGCombine(ISD::SRL);
1646   setTargetDAGCombine(ISD::OR);
1647   setTargetDAGCombine(ISD::AND);
1648   setTargetDAGCombine(ISD::ADD);
1649   setTargetDAGCombine(ISD::FADD);
1650   setTargetDAGCombine(ISD::FSUB);
1651   setTargetDAGCombine(ISD::FMA);
1652   setTargetDAGCombine(ISD::SUB);
1653   setTargetDAGCombine(ISD::LOAD);
1654   setTargetDAGCombine(ISD::MLOAD);
1655   setTargetDAGCombine(ISD::STORE);
1656   setTargetDAGCombine(ISD::MSTORE);
1657   setTargetDAGCombine(ISD::ZERO_EXTEND);
1658   setTargetDAGCombine(ISD::ANY_EXTEND);
1659   setTargetDAGCombine(ISD::SIGN_EXTEND);
1660   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1661   setTargetDAGCombine(ISD::TRUNCATE);
1662   setTargetDAGCombine(ISD::SINT_TO_FP);
1663   setTargetDAGCombine(ISD::SETCC);
1664   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1665   setTargetDAGCombine(ISD::BUILD_VECTOR);
1666   setTargetDAGCombine(ISD::MUL);
1667   setTargetDAGCombine(ISD::XOR);
1668
1669   computeRegisterProperties(Subtarget->getRegisterInfo());
1670
1671   // On Darwin, -Os means optimize for size without hurting performance,
1672   // do not reduce the limit.
1673   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1674   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1675   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1676   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1677   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1678   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1679   setPrefLoopAlignment(4); // 2^4 bytes.
1680
1681   // Predictable cmov don't hurt on atom because it's in-order.
1682   PredictableSelectIsExpensive = !Subtarget->isAtom();
1683   EnableExtLdPromotion = true;
1684   setPrefFunctionAlignment(4); // 2^4 bytes.
1685
1686   verifyIntrinsicTables();
1687 }
1688
1689 // This has so far only been implemented for 64-bit MachO.
1690 bool X86TargetLowering::useLoadStackGuardNode() const {
1691   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1692 }
1693
1694 TargetLoweringBase::LegalizeTypeAction
1695 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1696   if (ExperimentalVectorWideningLegalization &&
1697       VT.getVectorNumElements() != 1 &&
1698       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1699     return TypeWidenVector;
1700
1701   return TargetLoweringBase::getPreferredVectorAction(VT);
1702 }
1703
1704 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1705   if (!VT.isVector())
1706     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1707
1708   const unsigned NumElts = VT.getVectorNumElements();
1709   const EVT EltVT = VT.getVectorElementType();
1710   if (VT.is512BitVector()) {
1711     if (Subtarget->hasAVX512())
1712       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1713           EltVT == MVT::f32 || EltVT == MVT::f64)
1714         switch(NumElts) {
1715         case  8: return MVT::v8i1;
1716         case 16: return MVT::v16i1;
1717       }
1718     if (Subtarget->hasBWI())
1719       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1720         switch(NumElts) {
1721         case 32: return MVT::v32i1;
1722         case 64: return MVT::v64i1;
1723       }
1724   }
1725
1726   if (VT.is256BitVector() || VT.is128BitVector()) {
1727     if (Subtarget->hasVLX())
1728       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1729           EltVT == MVT::f32 || EltVT == MVT::f64)
1730         switch(NumElts) {
1731         case 2: return MVT::v2i1;
1732         case 4: return MVT::v4i1;
1733         case 8: return MVT::v8i1;
1734       }
1735     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1736       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1737         switch(NumElts) {
1738         case  8: return MVT::v8i1;
1739         case 16: return MVT::v16i1;
1740         case 32: return MVT::v32i1;
1741       }
1742   }
1743
1744   return VT.changeVectorElementTypeToInteger();
1745 }
1746
1747 /// Helper for getByValTypeAlignment to determine
1748 /// the desired ByVal argument alignment.
1749 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1750   if (MaxAlign == 16)
1751     return;
1752   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1753     if (VTy->getBitWidth() == 128)
1754       MaxAlign = 16;
1755   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1756     unsigned EltAlign = 0;
1757     getMaxByValAlign(ATy->getElementType(), EltAlign);
1758     if (EltAlign > MaxAlign)
1759       MaxAlign = EltAlign;
1760   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1761     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1762       unsigned EltAlign = 0;
1763       getMaxByValAlign(STy->getElementType(i), EltAlign);
1764       if (EltAlign > MaxAlign)
1765         MaxAlign = EltAlign;
1766       if (MaxAlign == 16)
1767         break;
1768     }
1769   }
1770 }
1771
1772 /// Return the desired alignment for ByVal aggregate
1773 /// function arguments in the caller parameter area. For X86, aggregates
1774 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1775 /// are at 4-byte boundaries.
1776 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1777   if (Subtarget->is64Bit()) {
1778     // Max of 8 and alignment of type.
1779     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1780     if (TyAlign > 8)
1781       return TyAlign;
1782     return 8;
1783   }
1784
1785   unsigned Align = 4;
1786   if (Subtarget->hasSSE1())
1787     getMaxByValAlign(Ty, Align);
1788   return Align;
1789 }
1790
1791 /// Returns the target specific optimal type for load
1792 /// and store operations as a result of memset, memcpy, and memmove
1793 /// lowering. If DstAlign is zero that means it's safe to destination
1794 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1795 /// means there isn't a need to check it against alignment requirement,
1796 /// probably because the source does not need to be loaded. If 'IsMemset' is
1797 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1798 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1799 /// source is constant so it does not need to be loaded.
1800 /// It returns EVT::Other if the type should be determined using generic
1801 /// target-independent logic.
1802 EVT
1803 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1804                                        unsigned DstAlign, unsigned SrcAlign,
1805                                        bool IsMemset, bool ZeroMemset,
1806                                        bool MemcpyStrSrc,
1807                                        MachineFunction &MF) const {
1808   const Function *F = MF.getFunction();
1809   if ((!IsMemset || ZeroMemset) &&
1810       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1811     if (Size >= 16 &&
1812         (Subtarget->isUnalignedMemAccessFast() ||
1813          ((DstAlign == 0 || DstAlign >= 16) &&
1814           (SrcAlign == 0 || SrcAlign >= 16)))) {
1815       if (Size >= 32) {
1816         if (Subtarget->hasInt256())
1817           return MVT::v8i32;
1818         if (Subtarget->hasFp256())
1819           return MVT::v8f32;
1820       }
1821       if (Subtarget->hasSSE2())
1822         return MVT::v4i32;
1823       if (Subtarget->hasSSE1())
1824         return MVT::v4f32;
1825     } else if (!MemcpyStrSrc && Size >= 8 &&
1826                !Subtarget->is64Bit() &&
1827                Subtarget->hasSSE2()) {
1828       // Do not use f64 to lower memcpy if source is string constant. It's
1829       // better to use i32 to avoid the loads.
1830       return MVT::f64;
1831     }
1832   }
1833   if (Subtarget->is64Bit() && Size >= 8)
1834     return MVT::i64;
1835   return MVT::i32;
1836 }
1837
1838 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1839   if (VT == MVT::f32)
1840     return X86ScalarSSEf32;
1841   else if (VT == MVT::f64)
1842     return X86ScalarSSEf64;
1843   return true;
1844 }
1845
1846 bool
1847 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1848                                                   unsigned,
1849                                                   unsigned,
1850                                                   bool *Fast) const {
1851   if (Fast)
1852     *Fast = Subtarget->isUnalignedMemAccessFast();
1853   return true;
1854 }
1855
1856 /// Return the entry encoding for a jump table in the
1857 /// current function.  The returned value is a member of the
1858 /// MachineJumpTableInfo::JTEntryKind enum.
1859 unsigned X86TargetLowering::getJumpTableEncoding() const {
1860   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1861   // symbol.
1862   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1863       Subtarget->isPICStyleGOT())
1864     return MachineJumpTableInfo::EK_Custom32;
1865
1866   // Otherwise, use the normal jump table encoding heuristics.
1867   return TargetLowering::getJumpTableEncoding();
1868 }
1869
1870 const MCExpr *
1871 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1872                                              const MachineBasicBlock *MBB,
1873                                              unsigned uid,MCContext &Ctx) const{
1874   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1875          Subtarget->isPICStyleGOT());
1876   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1877   // entries.
1878   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1879                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1880 }
1881
1882 /// Returns relocation base for the given PIC jumptable.
1883 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1884                                                     SelectionDAG &DAG) const {
1885   if (!Subtarget->is64Bit())
1886     // This doesn't have SDLoc associated with it, but is not really the
1887     // same as a Register.
1888     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1889   return Table;
1890 }
1891
1892 /// This returns the relocation base for the given PIC jumptable,
1893 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1894 const MCExpr *X86TargetLowering::
1895 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1896                              MCContext &Ctx) const {
1897   // X86-64 uses RIP relative addressing based on the jump table label.
1898   if (Subtarget->isPICStyleRIPRel())
1899     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1900
1901   // Otherwise, the reference is relative to the PIC base.
1902   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1903 }
1904
1905 std::pair<const TargetRegisterClass *, uint8_t>
1906 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1907                                            MVT VT) const {
1908   const TargetRegisterClass *RRC = nullptr;
1909   uint8_t Cost = 1;
1910   switch (VT.SimpleTy) {
1911   default:
1912     return TargetLowering::findRepresentativeClass(TRI, VT);
1913   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1914     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1915     break;
1916   case MVT::x86mmx:
1917     RRC = &X86::VR64RegClass;
1918     break;
1919   case MVT::f32: case MVT::f64:
1920   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1921   case MVT::v4f32: case MVT::v2f64:
1922   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1923   case MVT::v4f64:
1924     RRC = &X86::VR128RegClass;
1925     break;
1926   }
1927   return std::make_pair(RRC, Cost);
1928 }
1929
1930 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1931                                                unsigned &Offset) const {
1932   if (!Subtarget->isTargetLinux())
1933     return false;
1934
1935   if (Subtarget->is64Bit()) {
1936     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1937     Offset = 0x28;
1938     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1939       AddressSpace = 256;
1940     else
1941       AddressSpace = 257;
1942   } else {
1943     // %gs:0x14 on i386
1944     Offset = 0x14;
1945     AddressSpace = 256;
1946   }
1947   return true;
1948 }
1949
1950 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1951                                             unsigned DestAS) const {
1952   assert(SrcAS != DestAS && "Expected different address spaces!");
1953
1954   return SrcAS < 256 && DestAS < 256;
1955 }
1956
1957 //===----------------------------------------------------------------------===//
1958 //               Return Value Calling Convention Implementation
1959 //===----------------------------------------------------------------------===//
1960
1961 #include "X86GenCallingConv.inc"
1962
1963 bool
1964 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1965                                   MachineFunction &MF, bool isVarArg,
1966                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1967                         LLVMContext &Context) const {
1968   SmallVector<CCValAssign, 16> RVLocs;
1969   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1970   return CCInfo.CheckReturn(Outs, RetCC_X86);
1971 }
1972
1973 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1974   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1975   return ScratchRegs;
1976 }
1977
1978 SDValue
1979 X86TargetLowering::LowerReturn(SDValue Chain,
1980                                CallingConv::ID CallConv, bool isVarArg,
1981                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1982                                const SmallVectorImpl<SDValue> &OutVals,
1983                                SDLoc dl, SelectionDAG &DAG) const {
1984   MachineFunction &MF = DAG.getMachineFunction();
1985   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1986
1987   SmallVector<CCValAssign, 16> RVLocs;
1988   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1989   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1990
1991   SDValue Flag;
1992   SmallVector<SDValue, 6> RetOps;
1993   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1994   // Operand #1 = Bytes To Pop
1995   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1996                    MVT::i16));
1997
1998   // Copy the result values into the output registers.
1999   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2000     CCValAssign &VA = RVLocs[i];
2001     assert(VA.isRegLoc() && "Can only return in registers!");
2002     SDValue ValToCopy = OutVals[i];
2003     EVT ValVT = ValToCopy.getValueType();
2004
2005     // Promote values to the appropriate types.
2006     if (VA.getLocInfo() == CCValAssign::SExt)
2007       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2008     else if (VA.getLocInfo() == CCValAssign::ZExt)
2009       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2010     else if (VA.getLocInfo() == CCValAssign::AExt)
2011       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2012     else if (VA.getLocInfo() == CCValAssign::BCvt)
2013       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2014
2015     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2016            "Unexpected FP-extend for return value.");
2017
2018     // If this is x86-64, and we disabled SSE, we can't return FP values,
2019     // or SSE or MMX vectors.
2020     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2021          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2022           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2023       report_fatal_error("SSE register return with SSE disabled");
2024     }
2025     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2026     // llvm-gcc has never done it right and no one has noticed, so this
2027     // should be OK for now.
2028     if (ValVT == MVT::f64 &&
2029         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2030       report_fatal_error("SSE2 register return with SSE2 disabled");
2031
2032     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2033     // the RET instruction and handled by the FP Stackifier.
2034     if (VA.getLocReg() == X86::FP0 ||
2035         VA.getLocReg() == X86::FP1) {
2036       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2037       // change the value to the FP stack register class.
2038       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2039         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2040       RetOps.push_back(ValToCopy);
2041       // Don't emit a copytoreg.
2042       continue;
2043     }
2044
2045     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2046     // which is returned in RAX / RDX.
2047     if (Subtarget->is64Bit()) {
2048       if (ValVT == MVT::x86mmx) {
2049         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2050           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2051           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2052                                   ValToCopy);
2053           // If we don't have SSE2 available, convert to v4f32 so the generated
2054           // register is legal.
2055           if (!Subtarget->hasSSE2())
2056             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2057         }
2058       }
2059     }
2060
2061     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2062     Flag = Chain.getValue(1);
2063     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2064   }
2065
2066   // The x86-64 ABIs require that for returning structs by value we copy
2067   // the sret argument into %rax/%eax (depending on ABI) for the return.
2068   // Win32 requires us to put the sret argument to %eax as well.
2069   // We saved the argument into a virtual register in the entry block,
2070   // so now we copy the value out and into %rax/%eax.
2071   //
2072   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2073   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2074   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2075   // either case FuncInfo->setSRetReturnReg() will have been called.
2076   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2077     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2078            "No need for an sret register");
2079     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2080
2081     unsigned RetValReg
2082         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2083           X86::RAX : X86::EAX;
2084     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2085     Flag = Chain.getValue(1);
2086
2087     // RAX/EAX now acts like a return value.
2088     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2089   }
2090
2091   RetOps[0] = Chain;  // Update chain.
2092
2093   // Add the flag if we have it.
2094   if (Flag.getNode())
2095     RetOps.push_back(Flag);
2096
2097   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2098 }
2099
2100 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2101   if (N->getNumValues() != 1)
2102     return false;
2103   if (!N->hasNUsesOfValue(1, 0))
2104     return false;
2105
2106   SDValue TCChain = Chain;
2107   SDNode *Copy = *N->use_begin();
2108   if (Copy->getOpcode() == ISD::CopyToReg) {
2109     // If the copy has a glue operand, we conservatively assume it isn't safe to
2110     // perform a tail call.
2111     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2112       return false;
2113     TCChain = Copy->getOperand(0);
2114   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2115     return false;
2116
2117   bool HasRet = false;
2118   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2119        UI != UE; ++UI) {
2120     if (UI->getOpcode() != X86ISD::RET_FLAG)
2121       return false;
2122     // If we are returning more than one value, we can definitely
2123     // not make a tail call see PR19530
2124     if (UI->getNumOperands() > 4)
2125       return false;
2126     if (UI->getNumOperands() == 4 &&
2127         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2128       return false;
2129     HasRet = true;
2130   }
2131
2132   if (!HasRet)
2133     return false;
2134
2135   Chain = TCChain;
2136   return true;
2137 }
2138
2139 EVT
2140 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2141                                             ISD::NodeType ExtendKind) const {
2142   MVT ReturnMVT;
2143   // TODO: Is this also valid on 32-bit?
2144   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2145     ReturnMVT = MVT::i8;
2146   else
2147     ReturnMVT = MVT::i32;
2148
2149   EVT MinVT = getRegisterType(Context, ReturnMVT);
2150   return VT.bitsLT(MinVT) ? MinVT : VT;
2151 }
2152
2153 /// Lower the result values of a call into the
2154 /// appropriate copies out of appropriate physical registers.
2155 ///
2156 SDValue
2157 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2158                                    CallingConv::ID CallConv, bool isVarArg,
2159                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2160                                    SDLoc dl, SelectionDAG &DAG,
2161                                    SmallVectorImpl<SDValue> &InVals) const {
2162
2163   // Assign locations to each value returned by this call.
2164   SmallVector<CCValAssign, 16> RVLocs;
2165   bool Is64Bit = Subtarget->is64Bit();
2166   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2167                  *DAG.getContext());
2168   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2169
2170   // Copy all of the result registers out of their specified physreg.
2171   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2172     CCValAssign &VA = RVLocs[i];
2173     EVT CopyVT = VA.getValVT();
2174
2175     // If this is x86-64, and we disabled SSE, we can't return FP values
2176     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2177         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2178       report_fatal_error("SSE register return with SSE disabled");
2179     }
2180
2181     // If we prefer to use the value in xmm registers, copy it out as f80 and
2182     // use a truncate to move it from fp stack reg to xmm reg.
2183     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2184         isScalarFPTypeInSSEReg(VA.getValVT()))
2185       CopyVT = MVT::f80;
2186
2187     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2188                                CopyVT, InFlag).getValue(1);
2189     SDValue Val = Chain.getValue(0);
2190
2191     if (CopyVT != VA.getValVT())
2192       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2193                         // This truncation won't change the value.
2194                         DAG.getIntPtrConstant(1));
2195
2196     InFlag = Chain.getValue(2);
2197     InVals.push_back(Val);
2198   }
2199
2200   return Chain;
2201 }
2202
2203 //===----------------------------------------------------------------------===//
2204 //                C & StdCall & Fast Calling Convention implementation
2205 //===----------------------------------------------------------------------===//
2206 //  StdCall calling convention seems to be standard for many Windows' API
2207 //  routines and around. It differs from C calling convention just a little:
2208 //  callee should clean up the stack, not caller. Symbols should be also
2209 //  decorated in some fancy way :) It doesn't support any vector arguments.
2210 //  For info on fast calling convention see Fast Calling Convention (tail call)
2211 //  implementation LowerX86_32FastCCCallTo.
2212
2213 /// CallIsStructReturn - Determines whether a call uses struct return
2214 /// semantics.
2215 enum StructReturnType {
2216   NotStructReturn,
2217   RegStructReturn,
2218   StackStructReturn
2219 };
2220 static StructReturnType
2221 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2222   if (Outs.empty())
2223     return NotStructReturn;
2224
2225   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2226   if (!Flags.isSRet())
2227     return NotStructReturn;
2228   if (Flags.isInReg())
2229     return RegStructReturn;
2230   return StackStructReturn;
2231 }
2232
2233 /// Determines whether a function uses struct return semantics.
2234 static StructReturnType
2235 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2236   if (Ins.empty())
2237     return NotStructReturn;
2238
2239   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2240   if (!Flags.isSRet())
2241     return NotStructReturn;
2242   if (Flags.isInReg())
2243     return RegStructReturn;
2244   return StackStructReturn;
2245 }
2246
2247 /// Make a copy of an aggregate at address specified by "Src" to address
2248 /// "Dst" with size and alignment information specified by the specific
2249 /// parameter attribute. The copy will be passed as a byval function parameter.
2250 static SDValue
2251 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2252                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2253                           SDLoc dl) {
2254   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2255
2256   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2257                        /*isVolatile*/false, /*AlwaysInline=*/true,
2258                        MachinePointerInfo(), MachinePointerInfo());
2259 }
2260
2261 /// Return true if the calling convention is one that
2262 /// supports tail call optimization.
2263 static bool IsTailCallConvention(CallingConv::ID CC) {
2264   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2265           CC == CallingConv::HiPE);
2266 }
2267
2268 /// \brief Return true if the calling convention is a C calling convention.
2269 static bool IsCCallConvention(CallingConv::ID CC) {
2270   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2271           CC == CallingConv::X86_64_SysV);
2272 }
2273
2274 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2275   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2276     return false;
2277
2278   CallSite CS(CI);
2279   CallingConv::ID CalleeCC = CS.getCallingConv();
2280   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2281     return false;
2282
2283   return true;
2284 }
2285
2286 /// Return true if the function is being made into
2287 /// a tailcall target by changing its ABI.
2288 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2289                                    bool GuaranteedTailCallOpt) {
2290   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2291 }
2292
2293 SDValue
2294 X86TargetLowering::LowerMemArgument(SDValue Chain,
2295                                     CallingConv::ID CallConv,
2296                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2297                                     SDLoc dl, SelectionDAG &DAG,
2298                                     const CCValAssign &VA,
2299                                     MachineFrameInfo *MFI,
2300                                     unsigned i) const {
2301   // Create the nodes corresponding to a load from this parameter slot.
2302   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2303   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2304       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2305   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2306   EVT ValVT;
2307
2308   // If value is passed by pointer we have address passed instead of the value
2309   // itself.
2310   if (VA.getLocInfo() == CCValAssign::Indirect)
2311     ValVT = VA.getLocVT();
2312   else
2313     ValVT = VA.getValVT();
2314
2315   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2316   // changed with more analysis.
2317   // In case of tail call optimization mark all arguments mutable. Since they
2318   // could be overwritten by lowering of arguments in case of a tail call.
2319   if (Flags.isByVal()) {
2320     unsigned Bytes = Flags.getByValSize();
2321     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2322     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2323     return DAG.getFrameIndex(FI, getPointerTy());
2324   } else {
2325     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2326                                     VA.getLocMemOffset(), isImmutable);
2327     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2328     return DAG.getLoad(ValVT, dl, Chain, FIN,
2329                        MachinePointerInfo::getFixedStack(FI),
2330                        false, false, false, 0);
2331   }
2332 }
2333
2334 // FIXME: Get this from tablegen.
2335 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2336                                                 const X86Subtarget *Subtarget) {
2337   assert(Subtarget->is64Bit());
2338
2339   if (Subtarget->isCallingConvWin64(CallConv)) {
2340     static const MCPhysReg GPR64ArgRegsWin64[] = {
2341       X86::RCX, X86::RDX, X86::R8,  X86::R9
2342     };
2343     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2344   }
2345
2346   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2347     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2348   };
2349   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2350 }
2351
2352 // FIXME: Get this from tablegen.
2353 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2354                                                 CallingConv::ID CallConv,
2355                                                 const X86Subtarget *Subtarget) {
2356   assert(Subtarget->is64Bit());
2357   if (Subtarget->isCallingConvWin64(CallConv)) {
2358     // The XMM registers which might contain var arg parameters are shadowed
2359     // in their paired GPR.  So we only need to save the GPR to their home
2360     // slots.
2361     // TODO: __vectorcall will change this.
2362     return None;
2363   }
2364
2365   const Function *Fn = MF.getFunction();
2366   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2367   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2368          "SSE register cannot be used when SSE is disabled!");
2369   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2370       !Subtarget->hasSSE1())
2371     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2372     // registers.
2373     return None;
2374
2375   static const MCPhysReg XMMArgRegs64Bit[] = {
2376     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2377     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2378   };
2379   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2380 }
2381
2382 SDValue
2383 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2384                                         CallingConv::ID CallConv,
2385                                         bool isVarArg,
2386                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2387                                         SDLoc dl,
2388                                         SelectionDAG &DAG,
2389                                         SmallVectorImpl<SDValue> &InVals)
2390                                           const {
2391   MachineFunction &MF = DAG.getMachineFunction();
2392   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2393
2394   const Function* Fn = MF.getFunction();
2395   if (Fn->hasExternalLinkage() &&
2396       Subtarget->isTargetCygMing() &&
2397       Fn->getName() == "main")
2398     FuncInfo->setForceFramePointer(true);
2399
2400   MachineFrameInfo *MFI = MF.getFrameInfo();
2401   bool Is64Bit = Subtarget->is64Bit();
2402   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2403
2404   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2405          "Var args not supported with calling convention fastcc, ghc or hipe");
2406
2407   // Assign locations to all of the incoming arguments.
2408   SmallVector<CCValAssign, 16> ArgLocs;
2409   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2410
2411   // Allocate shadow area for Win64
2412   if (IsWin64)
2413     CCInfo.AllocateStack(32, 8);
2414
2415   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2416
2417   unsigned LastVal = ~0U;
2418   SDValue ArgValue;
2419   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2420     CCValAssign &VA = ArgLocs[i];
2421     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2422     // places.
2423     assert(VA.getValNo() != LastVal &&
2424            "Don't support value assigned to multiple locs yet");
2425     (void)LastVal;
2426     LastVal = VA.getValNo();
2427
2428     if (VA.isRegLoc()) {
2429       EVT RegVT = VA.getLocVT();
2430       const TargetRegisterClass *RC;
2431       if (RegVT == MVT::i32)
2432         RC = &X86::GR32RegClass;
2433       else if (Is64Bit && RegVT == MVT::i64)
2434         RC = &X86::GR64RegClass;
2435       else if (RegVT == MVT::f32)
2436         RC = &X86::FR32RegClass;
2437       else if (RegVT == MVT::f64)
2438         RC = &X86::FR64RegClass;
2439       else if (RegVT.is512BitVector())
2440         RC = &X86::VR512RegClass;
2441       else if (RegVT.is256BitVector())
2442         RC = &X86::VR256RegClass;
2443       else if (RegVT.is128BitVector())
2444         RC = &X86::VR128RegClass;
2445       else if (RegVT == MVT::x86mmx)
2446         RC = &X86::VR64RegClass;
2447       else if (RegVT == MVT::i1)
2448         RC = &X86::VK1RegClass;
2449       else if (RegVT == MVT::v8i1)
2450         RC = &X86::VK8RegClass;
2451       else if (RegVT == MVT::v16i1)
2452         RC = &X86::VK16RegClass;
2453       else if (RegVT == MVT::v32i1)
2454         RC = &X86::VK32RegClass;
2455       else if (RegVT == MVT::v64i1)
2456         RC = &X86::VK64RegClass;
2457       else
2458         llvm_unreachable("Unknown argument type!");
2459
2460       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2461       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2462
2463       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2464       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2465       // right size.
2466       if (VA.getLocInfo() == CCValAssign::SExt)
2467         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2468                                DAG.getValueType(VA.getValVT()));
2469       else if (VA.getLocInfo() == CCValAssign::ZExt)
2470         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2471                                DAG.getValueType(VA.getValVT()));
2472       else if (VA.getLocInfo() == CCValAssign::BCvt)
2473         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2474
2475       if (VA.isExtInLoc()) {
2476         // Handle MMX values passed in XMM regs.
2477         if (RegVT.isVector())
2478           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2479         else
2480           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2481       }
2482     } else {
2483       assert(VA.isMemLoc());
2484       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2485     }
2486
2487     // If value is passed via pointer - do a load.
2488     if (VA.getLocInfo() == CCValAssign::Indirect)
2489       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2490                              MachinePointerInfo(), false, false, false, 0);
2491
2492     InVals.push_back(ArgValue);
2493   }
2494
2495   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2496     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2497       // The x86-64 ABIs require that for returning structs by value we copy
2498       // the sret argument into %rax/%eax (depending on ABI) for the return.
2499       // Win32 requires us to put the sret argument to %eax as well.
2500       // Save the argument into a virtual register so that we can access it
2501       // from the return points.
2502       if (Ins[i].Flags.isSRet()) {
2503         unsigned Reg = FuncInfo->getSRetReturnReg();
2504         if (!Reg) {
2505           MVT PtrTy = getPointerTy();
2506           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2507           FuncInfo->setSRetReturnReg(Reg);
2508         }
2509         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2510         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2511         break;
2512       }
2513     }
2514   }
2515
2516   unsigned StackSize = CCInfo.getNextStackOffset();
2517   // Align stack specially for tail calls.
2518   if (FuncIsMadeTailCallSafe(CallConv,
2519                              MF.getTarget().Options.GuaranteedTailCallOpt))
2520     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2521
2522   // If the function takes variable number of arguments, make a frame index for
2523   // the start of the first vararg value... for expansion of llvm.va_start. We
2524   // can skip this if there are no va_start calls.
2525   if (MFI->hasVAStart() &&
2526       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2527                    CallConv != CallingConv::X86_ThisCall))) {
2528     FuncInfo->setVarArgsFrameIndex(
2529         MFI->CreateFixedObject(1, StackSize, true));
2530   }
2531
2532   // Figure out if XMM registers are in use.
2533   assert(!(MF.getTarget().Options.UseSoftFloat &&
2534            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2535          "SSE register cannot be used when SSE is disabled!");
2536
2537   // 64-bit calling conventions support varargs and register parameters, so we
2538   // have to do extra work to spill them in the prologue.
2539   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2540     // Find the first unallocated argument registers.
2541     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2542     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2543     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2544     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2545     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2546            "SSE register cannot be used when SSE is disabled!");
2547
2548     // Gather all the live in physical registers.
2549     SmallVector<SDValue, 6> LiveGPRs;
2550     SmallVector<SDValue, 8> LiveXMMRegs;
2551     SDValue ALVal;
2552     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2553       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2554       LiveGPRs.push_back(
2555           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2556     }
2557     if (!ArgXMMs.empty()) {
2558       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2559       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2560       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2561         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2562         LiveXMMRegs.push_back(
2563             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2564       }
2565     }
2566
2567     if (IsWin64) {
2568       const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2569       // Get to the caller-allocated home save location.  Add 8 to account
2570       // for the return address.
2571       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2572       FuncInfo->setRegSaveFrameIndex(
2573           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2574       // Fixup to set vararg frame on shadow area (4 x i64).
2575       if (NumIntRegs < 4)
2576         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2577     } else {
2578       // For X86-64, if there are vararg parameters that are passed via
2579       // registers, then we must store them to their spots on the stack so
2580       // they may be loaded by deferencing the result of va_next.
2581       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2582       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2583       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2584           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2585     }
2586
2587     // Store the integer parameter registers.
2588     SmallVector<SDValue, 8> MemOps;
2589     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2590                                       getPointerTy());
2591     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2592     for (SDValue Val : LiveGPRs) {
2593       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2594                                 DAG.getIntPtrConstant(Offset));
2595       SDValue Store =
2596         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2597                      MachinePointerInfo::getFixedStack(
2598                        FuncInfo->getRegSaveFrameIndex(), Offset),
2599                      false, false, 0);
2600       MemOps.push_back(Store);
2601       Offset += 8;
2602     }
2603
2604     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2605       // Now store the XMM (fp + vector) parameter registers.
2606       SmallVector<SDValue, 12> SaveXMMOps;
2607       SaveXMMOps.push_back(Chain);
2608       SaveXMMOps.push_back(ALVal);
2609       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2610                              FuncInfo->getRegSaveFrameIndex()));
2611       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2612                              FuncInfo->getVarArgsFPOffset()));
2613       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2614                         LiveXMMRegs.end());
2615       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2616                                    MVT::Other, SaveXMMOps));
2617     }
2618
2619     if (!MemOps.empty())
2620       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2621   }
2622
2623   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2624     // Find the largest legal vector type.
2625     MVT VecVT = MVT::Other;
2626     // FIXME: Only some x86_32 calling conventions support AVX512.
2627     if (Subtarget->hasAVX512() &&
2628         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2629                      CallConv == CallingConv::Intel_OCL_BI)))
2630       VecVT = MVT::v16f32;
2631     else if (Subtarget->hasAVX())
2632       VecVT = MVT::v8f32;
2633     else if (Subtarget->hasSSE2())
2634       VecVT = MVT::v4f32;
2635
2636     // We forward some GPRs and some vector types.
2637     SmallVector<MVT, 2> RegParmTypes;
2638     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2639     RegParmTypes.push_back(IntVT);
2640     if (VecVT != MVT::Other)
2641       RegParmTypes.push_back(VecVT);
2642
2643     // Compute the set of forwarded registers. The rest are scratch.
2644     SmallVectorImpl<ForwardedRegister> &Forwards =
2645         FuncInfo->getForwardedMustTailRegParms();
2646     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2647
2648     // Conservatively forward AL on x86_64, since it might be used for varargs.
2649     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2650       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2651       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2652     }
2653
2654     // Copy all forwards from physical to virtual registers.
2655     for (ForwardedRegister &F : Forwards) {
2656       // FIXME: Can we use a less constrained schedule?
2657       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2658       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2659       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2660     }
2661   }
2662
2663   // Some CCs need callee pop.
2664   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2665                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2666     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2667   } else {
2668     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2669     // If this is an sret function, the return should pop the hidden pointer.
2670     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2671         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2672         argsAreStructReturn(Ins) == StackStructReturn)
2673       FuncInfo->setBytesToPopOnReturn(4);
2674   }
2675
2676   if (!Is64Bit) {
2677     // RegSaveFrameIndex is X86-64 only.
2678     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2679     if (CallConv == CallingConv::X86_FastCall ||
2680         CallConv == CallingConv::X86_ThisCall)
2681       // fastcc functions can't have varargs.
2682       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2683   }
2684
2685   FuncInfo->setArgumentStackSize(StackSize);
2686
2687   return Chain;
2688 }
2689
2690 SDValue
2691 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2692                                     SDValue StackPtr, SDValue Arg,
2693                                     SDLoc dl, SelectionDAG &DAG,
2694                                     const CCValAssign &VA,
2695                                     ISD::ArgFlagsTy Flags) const {
2696   unsigned LocMemOffset = VA.getLocMemOffset();
2697   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2698   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2699   if (Flags.isByVal())
2700     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2701
2702   return DAG.getStore(Chain, dl, Arg, PtrOff,
2703                       MachinePointerInfo::getStack(LocMemOffset),
2704                       false, false, 0);
2705 }
2706
2707 /// Emit a load of return address if tail call
2708 /// optimization is performed and it is required.
2709 SDValue
2710 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2711                                            SDValue &OutRetAddr, SDValue Chain,
2712                                            bool IsTailCall, bool Is64Bit,
2713                                            int FPDiff, SDLoc dl) const {
2714   // Adjust the Return address stack slot.
2715   EVT VT = getPointerTy();
2716   OutRetAddr = getReturnAddressFrameIndex(DAG);
2717
2718   // Load the "old" Return address.
2719   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2720                            false, false, false, 0);
2721   return SDValue(OutRetAddr.getNode(), 1);
2722 }
2723
2724 /// Emit a store of the return address if tail call
2725 /// optimization is performed and it is required (FPDiff!=0).
2726 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2727                                         SDValue Chain, SDValue RetAddrFrIdx,
2728                                         EVT PtrVT, unsigned SlotSize,
2729                                         int FPDiff, SDLoc dl) {
2730   // Store the return address to the appropriate stack slot.
2731   if (!FPDiff) return Chain;
2732   // Calculate the new stack slot for the return address.
2733   int NewReturnAddrFI =
2734     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2735                                          false);
2736   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2737   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2738                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2739                        false, false, 0);
2740   return Chain;
2741 }
2742
2743 SDValue
2744 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2745                              SmallVectorImpl<SDValue> &InVals) const {
2746   SelectionDAG &DAG                     = CLI.DAG;
2747   SDLoc &dl                             = CLI.DL;
2748   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2749   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2750   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2751   SDValue Chain                         = CLI.Chain;
2752   SDValue Callee                        = CLI.Callee;
2753   CallingConv::ID CallConv              = CLI.CallConv;
2754   bool &isTailCall                      = CLI.IsTailCall;
2755   bool isVarArg                         = CLI.IsVarArg;
2756
2757   MachineFunction &MF = DAG.getMachineFunction();
2758   bool Is64Bit        = Subtarget->is64Bit();
2759   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2760   StructReturnType SR = callIsStructReturn(Outs);
2761   bool IsSibcall      = false;
2762   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2763
2764   if (MF.getTarget().Options.DisableTailCalls)
2765     isTailCall = false;
2766
2767   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2768   if (IsMustTail) {
2769     // Force this to be a tail call.  The verifier rules are enough to ensure
2770     // that we can lower this successfully without moving the return address
2771     // around.
2772     isTailCall = true;
2773   } else if (isTailCall) {
2774     // Check if it's really possible to do a tail call.
2775     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2776                     isVarArg, SR != NotStructReturn,
2777                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2778                     Outs, OutVals, Ins, DAG);
2779
2780     // Sibcalls are automatically detected tailcalls which do not require
2781     // ABI changes.
2782     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2783       IsSibcall = true;
2784
2785     if (isTailCall)
2786       ++NumTailCalls;
2787   }
2788
2789   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2790          "Var args not supported with calling convention fastcc, ghc or hipe");
2791
2792   // Analyze operands of the call, assigning locations to each operand.
2793   SmallVector<CCValAssign, 16> ArgLocs;
2794   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2795
2796   // Allocate shadow area for Win64
2797   if (IsWin64)
2798     CCInfo.AllocateStack(32, 8);
2799
2800   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2801
2802   // Get a count of how many bytes are to be pushed on the stack.
2803   unsigned NumBytes = CCInfo.getNextStackOffset();
2804   if (IsSibcall)
2805     // This is a sibcall. The memory operands are available in caller's
2806     // own caller's stack.
2807     NumBytes = 0;
2808   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2809            IsTailCallConvention(CallConv))
2810     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2811
2812   int FPDiff = 0;
2813   if (isTailCall && !IsSibcall && !IsMustTail) {
2814     // Lower arguments at fp - stackoffset + fpdiff.
2815     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2816
2817     FPDiff = NumBytesCallerPushed - NumBytes;
2818
2819     // Set the delta of movement of the returnaddr stackslot.
2820     // But only set if delta is greater than previous delta.
2821     if (FPDiff < X86Info->getTCReturnAddrDelta())
2822       X86Info->setTCReturnAddrDelta(FPDiff);
2823   }
2824
2825   unsigned NumBytesToPush = NumBytes;
2826   unsigned NumBytesToPop = NumBytes;
2827
2828   // If we have an inalloca argument, all stack space has already been allocated
2829   // for us and be right at the top of the stack.  We don't support multiple
2830   // arguments passed in memory when using inalloca.
2831   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2832     NumBytesToPush = 0;
2833     if (!ArgLocs.back().isMemLoc())
2834       report_fatal_error("cannot use inalloca attribute on a register "
2835                          "parameter");
2836     if (ArgLocs.back().getLocMemOffset() != 0)
2837       report_fatal_error("any parameter with the inalloca attribute must be "
2838                          "the only memory argument");
2839   }
2840
2841   if (!IsSibcall)
2842     Chain = DAG.getCALLSEQ_START(
2843         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2844
2845   SDValue RetAddrFrIdx;
2846   // Load return address for tail calls.
2847   if (isTailCall && FPDiff)
2848     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2849                                     Is64Bit, FPDiff, dl);
2850
2851   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2852   SmallVector<SDValue, 8> MemOpChains;
2853   SDValue StackPtr;
2854
2855   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2856   // of tail call optimization arguments are handle later.
2857   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2858   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2859     // Skip inalloca arguments, they have already been written.
2860     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2861     if (Flags.isInAlloca())
2862       continue;
2863
2864     CCValAssign &VA = ArgLocs[i];
2865     EVT RegVT = VA.getLocVT();
2866     SDValue Arg = OutVals[i];
2867     bool isByVal = Flags.isByVal();
2868
2869     // Promote the value if needed.
2870     switch (VA.getLocInfo()) {
2871     default: llvm_unreachable("Unknown loc info!");
2872     case CCValAssign::Full: break;
2873     case CCValAssign::SExt:
2874       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2875       break;
2876     case CCValAssign::ZExt:
2877       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2878       break;
2879     case CCValAssign::AExt:
2880       if (RegVT.is128BitVector()) {
2881         // Special case: passing MMX values in XMM registers.
2882         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2883         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2884         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2885       } else
2886         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2887       break;
2888     case CCValAssign::BCvt:
2889       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2890       break;
2891     case CCValAssign::Indirect: {
2892       // Store the argument.
2893       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2894       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2895       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2896                            MachinePointerInfo::getFixedStack(FI),
2897                            false, false, 0);
2898       Arg = SpillSlot;
2899       break;
2900     }
2901     }
2902
2903     if (VA.isRegLoc()) {
2904       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2905       if (isVarArg && IsWin64) {
2906         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2907         // shadow reg if callee is a varargs function.
2908         unsigned ShadowReg = 0;
2909         switch (VA.getLocReg()) {
2910         case X86::XMM0: ShadowReg = X86::RCX; break;
2911         case X86::XMM1: ShadowReg = X86::RDX; break;
2912         case X86::XMM2: ShadowReg = X86::R8; break;
2913         case X86::XMM3: ShadowReg = X86::R9; break;
2914         }
2915         if (ShadowReg)
2916           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2917       }
2918     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2919       assert(VA.isMemLoc());
2920       if (!StackPtr.getNode())
2921         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2922                                       getPointerTy());
2923       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2924                                              dl, DAG, VA, Flags));
2925     }
2926   }
2927
2928   if (!MemOpChains.empty())
2929     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2930
2931   if (Subtarget->isPICStyleGOT()) {
2932     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2933     // GOT pointer.
2934     if (!isTailCall) {
2935       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2936                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2937     } else {
2938       // If we are tail calling and generating PIC/GOT style code load the
2939       // address of the callee into ECX. The value in ecx is used as target of
2940       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2941       // for tail calls on PIC/GOT architectures. Normally we would just put the
2942       // address of GOT into ebx and then call target@PLT. But for tail calls
2943       // ebx would be restored (since ebx is callee saved) before jumping to the
2944       // target@PLT.
2945
2946       // Note: The actual moving to ECX is done further down.
2947       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2948       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2949           !G->getGlobal()->hasProtectedVisibility())
2950         Callee = LowerGlobalAddress(Callee, DAG);
2951       else if (isa<ExternalSymbolSDNode>(Callee))
2952         Callee = LowerExternalSymbol(Callee, DAG);
2953     }
2954   }
2955
2956   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2957     // From AMD64 ABI document:
2958     // For calls that may call functions that use varargs or stdargs
2959     // (prototype-less calls or calls to functions containing ellipsis (...) in
2960     // the declaration) %al is used as hidden argument to specify the number
2961     // of SSE registers used. The contents of %al do not need to match exactly
2962     // the number of registers, but must be an ubound on the number of SSE
2963     // registers used and is in the range 0 - 8 inclusive.
2964
2965     // Count the number of XMM registers allocated.
2966     static const MCPhysReg XMMArgRegs[] = {
2967       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2968       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2969     };
2970     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2971     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2972            && "SSE registers cannot be used when SSE is disabled");
2973
2974     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2975                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2976   }
2977
2978   if (isVarArg && IsMustTail) {
2979     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2980     for (const auto &F : Forwards) {
2981       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2982       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2983     }
2984   }
2985
2986   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2987   // don't need this because the eligibility check rejects calls that require
2988   // shuffling arguments passed in memory.
2989   if (!IsSibcall && isTailCall) {
2990     // Force all the incoming stack arguments to be loaded from the stack
2991     // before any new outgoing arguments are stored to the stack, because the
2992     // outgoing stack slots may alias the incoming argument stack slots, and
2993     // the alias isn't otherwise explicit. This is slightly more conservative
2994     // than necessary, because it means that each store effectively depends
2995     // on every argument instead of just those arguments it would clobber.
2996     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2997
2998     SmallVector<SDValue, 8> MemOpChains2;
2999     SDValue FIN;
3000     int FI = 0;
3001     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3002       CCValAssign &VA = ArgLocs[i];
3003       if (VA.isRegLoc())
3004         continue;
3005       assert(VA.isMemLoc());
3006       SDValue Arg = OutVals[i];
3007       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3008       // Skip inalloca arguments.  They don't require any work.
3009       if (Flags.isInAlloca())
3010         continue;
3011       // Create frame index.
3012       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3013       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3014       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3015       FIN = DAG.getFrameIndex(FI, getPointerTy());
3016
3017       if (Flags.isByVal()) {
3018         // Copy relative to framepointer.
3019         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3020         if (!StackPtr.getNode())
3021           StackPtr = DAG.getCopyFromReg(Chain, dl,
3022                                         RegInfo->getStackRegister(),
3023                                         getPointerTy());
3024         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3025
3026         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3027                                                          ArgChain,
3028                                                          Flags, DAG, dl));
3029       } else {
3030         // Store relative to framepointer.
3031         MemOpChains2.push_back(
3032           DAG.getStore(ArgChain, dl, Arg, FIN,
3033                        MachinePointerInfo::getFixedStack(FI),
3034                        false, false, 0));
3035       }
3036     }
3037
3038     if (!MemOpChains2.empty())
3039       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3040
3041     // Store the return address to the appropriate stack slot.
3042     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3043                                      getPointerTy(), RegInfo->getSlotSize(),
3044                                      FPDiff, dl);
3045   }
3046
3047   // Build a sequence of copy-to-reg nodes chained together with token chain
3048   // and flag operands which copy the outgoing args into registers.
3049   SDValue InFlag;
3050   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3051     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3052                              RegsToPass[i].second, InFlag);
3053     InFlag = Chain.getValue(1);
3054   }
3055
3056   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3057     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3058     // In the 64-bit large code model, we have to make all calls
3059     // through a register, since the call instruction's 32-bit
3060     // pc-relative offset may not be large enough to hold the whole
3061     // address.
3062   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3063     // If the callee is a GlobalAddress node (quite common, every direct call
3064     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3065     // it.
3066     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3067
3068     // We should use extra load for direct calls to dllimported functions in
3069     // non-JIT mode.
3070     const GlobalValue *GV = G->getGlobal();
3071     if (!GV->hasDLLImportStorageClass()) {
3072       unsigned char OpFlags = 0;
3073       bool ExtraLoad = false;
3074       unsigned WrapperKind = ISD::DELETED_NODE;
3075
3076       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3077       // external symbols most go through the PLT in PIC mode.  If the symbol
3078       // has hidden or protected visibility, or if it is static or local, then
3079       // we don't need to use the PLT - we can directly call it.
3080       if (Subtarget->isTargetELF() &&
3081           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3082           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3083         OpFlags = X86II::MO_PLT;
3084       } else if (Subtarget->isPICStyleStubAny() &&
3085                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3086                  (!Subtarget->getTargetTriple().isMacOSX() ||
3087                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3088         // PC-relative references to external symbols should go through $stub,
3089         // unless we're building with the leopard linker or later, which
3090         // automatically synthesizes these stubs.
3091         OpFlags = X86II::MO_DARWIN_STUB;
3092       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3093                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3094         // If the function is marked as non-lazy, generate an indirect call
3095         // which loads from the GOT directly. This avoids runtime overhead
3096         // at the cost of eager binding (and one extra byte of encoding).
3097         OpFlags = X86II::MO_GOTPCREL;
3098         WrapperKind = X86ISD::WrapperRIP;
3099         ExtraLoad = true;
3100       }
3101
3102       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3103                                           G->getOffset(), OpFlags);
3104
3105       // Add a wrapper if needed.
3106       if (WrapperKind != ISD::DELETED_NODE)
3107         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3108       // Add extra indirection if needed.
3109       if (ExtraLoad)
3110         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3111                              MachinePointerInfo::getGOT(),
3112                              false, false, false, 0);
3113     }
3114   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3115     unsigned char OpFlags = 0;
3116
3117     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3118     // external symbols should go through the PLT.
3119     if (Subtarget->isTargetELF() &&
3120         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3121       OpFlags = X86II::MO_PLT;
3122     } else if (Subtarget->isPICStyleStubAny() &&
3123                (!Subtarget->getTargetTriple().isMacOSX() ||
3124                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3125       // PC-relative references to external symbols should go through $stub,
3126       // unless we're building with the leopard linker or later, which
3127       // automatically synthesizes these stubs.
3128       OpFlags = X86II::MO_DARWIN_STUB;
3129     }
3130
3131     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3132                                          OpFlags);
3133   } else if (Subtarget->isTarget64BitILP32() &&
3134              Callee->getValueType(0) == MVT::i32) {
3135     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3136     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3137   }
3138
3139   // Returns a chain & a flag for retval copy to use.
3140   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3141   SmallVector<SDValue, 8> Ops;
3142
3143   if (!IsSibcall && isTailCall) {
3144     Chain = DAG.getCALLSEQ_END(Chain,
3145                                DAG.getIntPtrConstant(NumBytesToPop, true),
3146                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3147     InFlag = Chain.getValue(1);
3148   }
3149
3150   Ops.push_back(Chain);
3151   Ops.push_back(Callee);
3152
3153   if (isTailCall)
3154     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3155
3156   // Add argument registers to the end of the list so that they are known live
3157   // into the call.
3158   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3159     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3160                                   RegsToPass[i].second.getValueType()));
3161
3162   // Add a register mask operand representing the call-preserved registers.
3163   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3164   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3165   assert(Mask && "Missing call preserved mask for calling convention");
3166   Ops.push_back(DAG.getRegisterMask(Mask));
3167
3168   if (InFlag.getNode())
3169     Ops.push_back(InFlag);
3170
3171   if (isTailCall) {
3172     // We used to do:
3173     //// If this is the first return lowered for this function, add the regs
3174     //// to the liveout set for the function.
3175     // This isn't right, although it's probably harmless on x86; liveouts
3176     // should be computed from returns not tail calls.  Consider a void
3177     // function making a tail call to a function returning int.
3178     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3179   }
3180
3181   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3182   InFlag = Chain.getValue(1);
3183
3184   // Create the CALLSEQ_END node.
3185   unsigned NumBytesForCalleeToPop;
3186   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3187                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3188     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3189   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3190            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3191            SR == StackStructReturn)
3192     // If this is a call to a struct-return function, the callee
3193     // pops the hidden struct pointer, so we have to push it back.
3194     // This is common for Darwin/X86, Linux & Mingw32 targets.
3195     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3196     NumBytesForCalleeToPop = 4;
3197   else
3198     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3199
3200   // Returns a flag for retval copy to use.
3201   if (!IsSibcall) {
3202     Chain = DAG.getCALLSEQ_END(Chain,
3203                                DAG.getIntPtrConstant(NumBytesToPop, true),
3204                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3205                                                      true),
3206                                InFlag, dl);
3207     InFlag = Chain.getValue(1);
3208   }
3209
3210   // Handle result values, copying them out of physregs into vregs that we
3211   // return.
3212   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3213                          Ins, dl, DAG, InVals);
3214 }
3215
3216 //===----------------------------------------------------------------------===//
3217 //                Fast Calling Convention (tail call) implementation
3218 //===----------------------------------------------------------------------===//
3219
3220 //  Like std call, callee cleans arguments, convention except that ECX is
3221 //  reserved for storing the tail called function address. Only 2 registers are
3222 //  free for argument passing (inreg). Tail call optimization is performed
3223 //  provided:
3224 //                * tailcallopt is enabled
3225 //                * caller/callee are fastcc
3226 //  On X86_64 architecture with GOT-style position independent code only local
3227 //  (within module) calls are supported at the moment.
3228 //  To keep the stack aligned according to platform abi the function
3229 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3230 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3231 //  If a tail called function callee has more arguments than the caller the
3232 //  caller needs to make sure that there is room to move the RETADDR to. This is
3233 //  achieved by reserving an area the size of the argument delta right after the
3234 //  original RETADDR, but before the saved framepointer or the spilled registers
3235 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3236 //  stack layout:
3237 //    arg1
3238 //    arg2
3239 //    RETADDR
3240 //    [ new RETADDR
3241 //      move area ]
3242 //    (possible EBP)
3243 //    ESI
3244 //    EDI
3245 //    local1 ..
3246
3247 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3248 /// for a 16 byte align requirement.
3249 unsigned
3250 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3251                                                SelectionDAG& DAG) const {
3252   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3253   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3254   unsigned StackAlignment = TFI.getStackAlignment();
3255   uint64_t AlignMask = StackAlignment - 1;
3256   int64_t Offset = StackSize;
3257   unsigned SlotSize = RegInfo->getSlotSize();
3258   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3259     // Number smaller than 12 so just add the difference.
3260     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3261   } else {
3262     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3263     Offset = ((~AlignMask) & Offset) + StackAlignment +
3264       (StackAlignment-SlotSize);
3265   }
3266   return Offset;
3267 }
3268
3269 /// MatchingStackOffset - Return true if the given stack call argument is
3270 /// already available in the same position (relatively) of the caller's
3271 /// incoming argument stack.
3272 static
3273 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3274                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3275                          const X86InstrInfo *TII) {
3276   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3277   int FI = INT_MAX;
3278   if (Arg.getOpcode() == ISD::CopyFromReg) {
3279     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3280     if (!TargetRegisterInfo::isVirtualRegister(VR))
3281       return false;
3282     MachineInstr *Def = MRI->getVRegDef(VR);
3283     if (!Def)
3284       return false;
3285     if (!Flags.isByVal()) {
3286       if (!TII->isLoadFromStackSlot(Def, FI))
3287         return false;
3288     } else {
3289       unsigned Opcode = Def->getOpcode();
3290       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3291            Opcode == X86::LEA64_32r) &&
3292           Def->getOperand(1).isFI()) {
3293         FI = Def->getOperand(1).getIndex();
3294         Bytes = Flags.getByValSize();
3295       } else
3296         return false;
3297     }
3298   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3299     if (Flags.isByVal())
3300       // ByVal argument is passed in as a pointer but it's now being
3301       // dereferenced. e.g.
3302       // define @foo(%struct.X* %A) {
3303       //   tail call @bar(%struct.X* byval %A)
3304       // }
3305       return false;
3306     SDValue Ptr = Ld->getBasePtr();
3307     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3308     if (!FINode)
3309       return false;
3310     FI = FINode->getIndex();
3311   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3312     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3313     FI = FINode->getIndex();
3314     Bytes = Flags.getByValSize();
3315   } else
3316     return false;
3317
3318   assert(FI != INT_MAX);
3319   if (!MFI->isFixedObjectIndex(FI))
3320     return false;
3321   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3322 }
3323
3324 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3325 /// for tail call optimization. Targets which want to do tail call
3326 /// optimization should implement this function.
3327 bool
3328 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3329                                                      CallingConv::ID CalleeCC,
3330                                                      bool isVarArg,
3331                                                      bool isCalleeStructRet,
3332                                                      bool isCallerStructRet,
3333                                                      Type *RetTy,
3334                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3335                                     const SmallVectorImpl<SDValue> &OutVals,
3336                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3337                                                      SelectionDAG &DAG) const {
3338   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3339     return false;
3340
3341   // If -tailcallopt is specified, make fastcc functions tail-callable.
3342   const MachineFunction &MF = DAG.getMachineFunction();
3343   const Function *CallerF = MF.getFunction();
3344
3345   // If the function return type is x86_fp80 and the callee return type is not,
3346   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3347   // perform a tailcall optimization here.
3348   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3349     return false;
3350
3351   CallingConv::ID CallerCC = CallerF->getCallingConv();
3352   bool CCMatch = CallerCC == CalleeCC;
3353   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3354   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3355
3356   // Win64 functions have extra shadow space for argument homing. Don't do the
3357   // sibcall if the caller and callee have mismatched expectations for this
3358   // space.
3359   if (IsCalleeWin64 != IsCallerWin64)
3360     return false;
3361
3362   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3363     if (IsTailCallConvention(CalleeCC) && CCMatch)
3364       return true;
3365     return false;
3366   }
3367
3368   // Look for obvious safe cases to perform tail call optimization that do not
3369   // require ABI changes. This is what gcc calls sibcall.
3370
3371   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3372   // emit a special epilogue.
3373   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3374   if (RegInfo->needsStackRealignment(MF))
3375     return false;
3376
3377   // Also avoid sibcall optimization if either caller or callee uses struct
3378   // return semantics.
3379   if (isCalleeStructRet || isCallerStructRet)
3380     return false;
3381
3382   // An stdcall/thiscall caller is expected to clean up its arguments; the
3383   // callee isn't going to do that.
3384   // FIXME: this is more restrictive than needed. We could produce a tailcall
3385   // when the stack adjustment matches. For example, with a thiscall that takes
3386   // only one argument.
3387   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3388                    CallerCC == CallingConv::X86_ThisCall))
3389     return false;
3390
3391   // Do not sibcall optimize vararg calls unless all arguments are passed via
3392   // registers.
3393   if (isVarArg && !Outs.empty()) {
3394
3395     // Optimizing for varargs on Win64 is unlikely to be safe without
3396     // additional testing.
3397     if (IsCalleeWin64 || IsCallerWin64)
3398       return false;
3399
3400     SmallVector<CCValAssign, 16> ArgLocs;
3401     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3402                    *DAG.getContext());
3403
3404     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3405     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3406       if (!ArgLocs[i].isRegLoc())
3407         return false;
3408   }
3409
3410   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3411   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3412   // this into a sibcall.
3413   bool Unused = false;
3414   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3415     if (!Ins[i].Used) {
3416       Unused = true;
3417       break;
3418     }
3419   }
3420   if (Unused) {
3421     SmallVector<CCValAssign, 16> RVLocs;
3422     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3423                    *DAG.getContext());
3424     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3425     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3426       CCValAssign &VA = RVLocs[i];
3427       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3428         return false;
3429     }
3430   }
3431
3432   // If the calling conventions do not match, then we'd better make sure the
3433   // results are returned in the same way as what the caller expects.
3434   if (!CCMatch) {
3435     SmallVector<CCValAssign, 16> RVLocs1;
3436     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3437                     *DAG.getContext());
3438     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3439
3440     SmallVector<CCValAssign, 16> RVLocs2;
3441     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3442                     *DAG.getContext());
3443     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3444
3445     if (RVLocs1.size() != RVLocs2.size())
3446       return false;
3447     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3448       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3449         return false;
3450       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3451         return false;
3452       if (RVLocs1[i].isRegLoc()) {
3453         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3454           return false;
3455       } else {
3456         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3457           return false;
3458       }
3459     }
3460   }
3461
3462   // If the callee takes no arguments then go on to check the results of the
3463   // call.
3464   if (!Outs.empty()) {
3465     // Check if stack adjustment is needed. For now, do not do this if any
3466     // argument is passed on the stack.
3467     SmallVector<CCValAssign, 16> ArgLocs;
3468     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3469                    *DAG.getContext());
3470
3471     // Allocate shadow area for Win64
3472     if (IsCalleeWin64)
3473       CCInfo.AllocateStack(32, 8);
3474
3475     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3476     if (CCInfo.getNextStackOffset()) {
3477       MachineFunction &MF = DAG.getMachineFunction();
3478       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3479         return false;
3480
3481       // Check if the arguments are already laid out in the right way as
3482       // the caller's fixed stack objects.
3483       MachineFrameInfo *MFI = MF.getFrameInfo();
3484       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3485       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3486       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3487         CCValAssign &VA = ArgLocs[i];
3488         SDValue Arg = OutVals[i];
3489         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3490         if (VA.getLocInfo() == CCValAssign::Indirect)
3491           return false;
3492         if (!VA.isRegLoc()) {
3493           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3494                                    MFI, MRI, TII))
3495             return false;
3496         }
3497       }
3498     }
3499
3500     // If the tailcall address may be in a register, then make sure it's
3501     // possible to register allocate for it. In 32-bit, the call address can
3502     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3503     // callee-saved registers are restored. These happen to be the same
3504     // registers used to pass 'inreg' arguments so watch out for those.
3505     if (!Subtarget->is64Bit() &&
3506         ((!isa<GlobalAddressSDNode>(Callee) &&
3507           !isa<ExternalSymbolSDNode>(Callee)) ||
3508          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3509       unsigned NumInRegs = 0;
3510       // In PIC we need an extra register to formulate the address computation
3511       // for the callee.
3512       unsigned MaxInRegs =
3513         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3514
3515       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3516         CCValAssign &VA = ArgLocs[i];
3517         if (!VA.isRegLoc())
3518           continue;
3519         unsigned Reg = VA.getLocReg();
3520         switch (Reg) {
3521         default: break;
3522         case X86::EAX: case X86::EDX: case X86::ECX:
3523           if (++NumInRegs == MaxInRegs)
3524             return false;
3525           break;
3526         }
3527       }
3528     }
3529   }
3530
3531   return true;
3532 }
3533
3534 FastISel *
3535 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3536                                   const TargetLibraryInfo *libInfo) const {
3537   return X86::createFastISel(funcInfo, libInfo);
3538 }
3539
3540 //===----------------------------------------------------------------------===//
3541 //                           Other Lowering Hooks
3542 //===----------------------------------------------------------------------===//
3543
3544 static bool MayFoldLoad(SDValue Op) {
3545   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3546 }
3547
3548 static bool MayFoldIntoStore(SDValue Op) {
3549   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3550 }
3551
3552 static bool isTargetShuffle(unsigned Opcode) {
3553   switch(Opcode) {
3554   default: return false;
3555   case X86ISD::BLENDI:
3556   case X86ISD::PSHUFB:
3557   case X86ISD::PSHUFD:
3558   case X86ISD::PSHUFHW:
3559   case X86ISD::PSHUFLW:
3560   case X86ISD::SHUFP:
3561   case X86ISD::PALIGNR:
3562   case X86ISD::MOVLHPS:
3563   case X86ISD::MOVLHPD:
3564   case X86ISD::MOVHLPS:
3565   case X86ISD::MOVLPS:
3566   case X86ISD::MOVLPD:
3567   case X86ISD::MOVSHDUP:
3568   case X86ISD::MOVSLDUP:
3569   case X86ISD::MOVDDUP:
3570   case X86ISD::MOVSS:
3571   case X86ISD::MOVSD:
3572   case X86ISD::UNPCKL:
3573   case X86ISD::UNPCKH:
3574   case X86ISD::VPERMILPI:
3575   case X86ISD::VPERM2X128:
3576   case X86ISD::VPERMI:
3577     return true;
3578   }
3579 }
3580
3581 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3582                                     SDValue V1, unsigned TargetMask,
3583                                     SelectionDAG &DAG) {
3584   switch(Opc) {
3585   default: llvm_unreachable("Unknown x86 shuffle node");
3586   case X86ISD::PSHUFD:
3587   case X86ISD::PSHUFHW:
3588   case X86ISD::PSHUFLW:
3589   case X86ISD::VPERMILPI:
3590   case X86ISD::VPERMI:
3591     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3592   }
3593 }
3594
3595 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3596                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3597   switch(Opc) {
3598   default: llvm_unreachable("Unknown x86 shuffle node");
3599   case X86ISD::MOVLHPS:
3600   case X86ISD::MOVLHPD:
3601   case X86ISD::MOVHLPS:
3602   case X86ISD::MOVLPS:
3603   case X86ISD::MOVLPD:
3604   case X86ISD::MOVSS:
3605   case X86ISD::MOVSD:
3606   case X86ISD::UNPCKL:
3607   case X86ISD::UNPCKH:
3608     return DAG.getNode(Opc, dl, VT, V1, V2);
3609   }
3610 }
3611
3612 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3613   MachineFunction &MF = DAG.getMachineFunction();
3614   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3615   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3616   int ReturnAddrIndex = FuncInfo->getRAIndex();
3617
3618   if (ReturnAddrIndex == 0) {
3619     // Set up a frame object for the return address.
3620     unsigned SlotSize = RegInfo->getSlotSize();
3621     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3622                                                            -(int64_t)SlotSize,
3623                                                            false);
3624     FuncInfo->setRAIndex(ReturnAddrIndex);
3625   }
3626
3627   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3628 }
3629
3630 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3631                                        bool hasSymbolicDisplacement) {
3632   // Offset should fit into 32 bit immediate field.
3633   if (!isInt<32>(Offset))
3634     return false;
3635
3636   // If we don't have a symbolic displacement - we don't have any extra
3637   // restrictions.
3638   if (!hasSymbolicDisplacement)
3639     return true;
3640
3641   // FIXME: Some tweaks might be needed for medium code model.
3642   if (M != CodeModel::Small && M != CodeModel::Kernel)
3643     return false;
3644
3645   // For small code model we assume that latest object is 16MB before end of 31
3646   // bits boundary. We may also accept pretty large negative constants knowing
3647   // that all objects are in the positive half of address space.
3648   if (M == CodeModel::Small && Offset < 16*1024*1024)
3649     return true;
3650
3651   // For kernel code model we know that all object resist in the negative half
3652   // of 32bits address space. We may not accept negative offsets, since they may
3653   // be just off and we may accept pretty large positive ones.
3654   if (M == CodeModel::Kernel && Offset >= 0)
3655     return true;
3656
3657   return false;
3658 }
3659
3660 /// isCalleePop - Determines whether the callee is required to pop its
3661 /// own arguments. Callee pop is necessary to support tail calls.
3662 bool X86::isCalleePop(CallingConv::ID CallingConv,
3663                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3664   switch (CallingConv) {
3665   default:
3666     return false;
3667   case CallingConv::X86_StdCall:
3668   case CallingConv::X86_FastCall:
3669   case CallingConv::X86_ThisCall:
3670     return !is64Bit;
3671   case CallingConv::Fast:
3672   case CallingConv::GHC:
3673   case CallingConv::HiPE:
3674     if (IsVarArg)
3675       return false;
3676     return TailCallOpt;
3677   }
3678 }
3679
3680 /// \brief Return true if the condition is an unsigned comparison operation.
3681 static bool isX86CCUnsigned(unsigned X86CC) {
3682   switch (X86CC) {
3683   default: llvm_unreachable("Invalid integer condition!");
3684   case X86::COND_E:     return true;
3685   case X86::COND_G:     return false;
3686   case X86::COND_GE:    return false;
3687   case X86::COND_L:     return false;
3688   case X86::COND_LE:    return false;
3689   case X86::COND_NE:    return true;
3690   case X86::COND_B:     return true;
3691   case X86::COND_A:     return true;
3692   case X86::COND_BE:    return true;
3693   case X86::COND_AE:    return true;
3694   }
3695   llvm_unreachable("covered switch fell through?!");
3696 }
3697
3698 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3699 /// specific condition code, returning the condition code and the LHS/RHS of the
3700 /// comparison to make.
3701 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3702                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3703   if (!isFP) {
3704     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3705       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3706         // X > -1   -> X == 0, jump !sign.
3707         RHS = DAG.getConstant(0, RHS.getValueType());
3708         return X86::COND_NS;
3709       }
3710       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3711         // X < 0   -> X == 0, jump on sign.
3712         return X86::COND_S;
3713       }
3714       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3715         // X < 1   -> X <= 0
3716         RHS = DAG.getConstant(0, RHS.getValueType());
3717         return X86::COND_LE;
3718       }
3719     }
3720
3721     switch (SetCCOpcode) {
3722     default: llvm_unreachable("Invalid integer condition!");
3723     case ISD::SETEQ:  return X86::COND_E;
3724     case ISD::SETGT:  return X86::COND_G;
3725     case ISD::SETGE:  return X86::COND_GE;
3726     case ISD::SETLT:  return X86::COND_L;
3727     case ISD::SETLE:  return X86::COND_LE;
3728     case ISD::SETNE:  return X86::COND_NE;
3729     case ISD::SETULT: return X86::COND_B;
3730     case ISD::SETUGT: return X86::COND_A;
3731     case ISD::SETULE: return X86::COND_BE;
3732     case ISD::SETUGE: return X86::COND_AE;
3733     }
3734   }
3735
3736   // First determine if it is required or is profitable to flip the operands.
3737
3738   // If LHS is a foldable load, but RHS is not, flip the condition.
3739   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3740       !ISD::isNON_EXTLoad(RHS.getNode())) {
3741     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3742     std::swap(LHS, RHS);
3743   }
3744
3745   switch (SetCCOpcode) {
3746   default: break;
3747   case ISD::SETOLT:
3748   case ISD::SETOLE:
3749   case ISD::SETUGT:
3750   case ISD::SETUGE:
3751     std::swap(LHS, RHS);
3752     break;
3753   }
3754
3755   // On a floating point condition, the flags are set as follows:
3756   // ZF  PF  CF   op
3757   //  0 | 0 | 0 | X > Y
3758   //  0 | 0 | 1 | X < Y
3759   //  1 | 0 | 0 | X == Y
3760   //  1 | 1 | 1 | unordered
3761   switch (SetCCOpcode) {
3762   default: llvm_unreachable("Condcode should be pre-legalized away");
3763   case ISD::SETUEQ:
3764   case ISD::SETEQ:   return X86::COND_E;
3765   case ISD::SETOLT:              // flipped
3766   case ISD::SETOGT:
3767   case ISD::SETGT:   return X86::COND_A;
3768   case ISD::SETOLE:              // flipped
3769   case ISD::SETOGE:
3770   case ISD::SETGE:   return X86::COND_AE;
3771   case ISD::SETUGT:              // flipped
3772   case ISD::SETULT:
3773   case ISD::SETLT:   return X86::COND_B;
3774   case ISD::SETUGE:              // flipped
3775   case ISD::SETULE:
3776   case ISD::SETLE:   return X86::COND_BE;
3777   case ISD::SETONE:
3778   case ISD::SETNE:   return X86::COND_NE;
3779   case ISD::SETUO:   return X86::COND_P;
3780   case ISD::SETO:    return X86::COND_NP;
3781   case ISD::SETOEQ:
3782   case ISD::SETUNE:  return X86::COND_INVALID;
3783   }
3784 }
3785
3786 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3787 /// code. Current x86 isa includes the following FP cmov instructions:
3788 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3789 static bool hasFPCMov(unsigned X86CC) {
3790   switch (X86CC) {
3791   default:
3792     return false;
3793   case X86::COND_B:
3794   case X86::COND_BE:
3795   case X86::COND_E:
3796   case X86::COND_P:
3797   case X86::COND_A:
3798   case X86::COND_AE:
3799   case X86::COND_NE:
3800   case X86::COND_NP:
3801     return true;
3802   }
3803 }
3804
3805 /// isFPImmLegal - Returns true if the target can instruction select the
3806 /// specified FP immediate natively. If false, the legalizer will
3807 /// materialize the FP immediate as a load from a constant pool.
3808 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3809   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3810     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3811       return true;
3812   }
3813   return false;
3814 }
3815
3816 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3817                                               ISD::LoadExtType ExtTy,
3818                                               EVT NewVT) const {
3819   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3820   // relocation target a movq or addq instruction: don't let the load shrink.
3821   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3822   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3823     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3824       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3825   return true;
3826 }
3827
3828 /// \brief Returns true if it is beneficial to convert a load of a constant
3829 /// to just the constant itself.
3830 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3831                                                           Type *Ty) const {
3832   assert(Ty->isIntegerTy());
3833
3834   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3835   if (BitSize == 0 || BitSize > 64)
3836     return false;
3837   return true;
3838 }
3839
3840 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3841                                                 unsigned Index) const {
3842   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3843     return false;
3844
3845   return (Index == 0 || Index == ResVT.getVectorNumElements());
3846 }
3847
3848 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3849   // Speculate cttz only if we can directly use TZCNT.
3850   return Subtarget->hasBMI();
3851 }
3852
3853 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3854   // Speculate ctlz only if we can directly use LZCNT.
3855   return Subtarget->hasLZCNT();
3856 }
3857
3858 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3859 /// the specified range (L, H].
3860 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3861   return (Val < 0) || (Val >= Low && Val < Hi);
3862 }
3863
3864 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3865 /// specified value.
3866 static bool isUndefOrEqual(int Val, int CmpVal) {
3867   return (Val < 0 || Val == CmpVal);
3868 }
3869
3870 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3871 /// from position Pos and ending in Pos+Size, falls within the specified
3872 /// sequential range (Low, Low+Size]. or is undef.
3873 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3874                                        unsigned Pos, unsigned Size, int Low) {
3875   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3876     if (!isUndefOrEqual(Mask[i], Low))
3877       return false;
3878   return true;
3879 }
3880
3881 /// isVEXTRACTIndex - Return true if the specified
3882 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3883 /// suitable for instruction that extract 128 or 256 bit vectors
3884 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3885   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3886   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3887     return false;
3888
3889   // The index should be aligned on a vecWidth-bit boundary.
3890   uint64_t Index =
3891     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3892
3893   MVT VT = N->getSimpleValueType(0);
3894   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3895   bool Result = (Index * ElSize) % vecWidth == 0;
3896
3897   return Result;
3898 }
3899
3900 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3901 /// operand specifies a subvector insert that is suitable for input to
3902 /// insertion of 128 or 256-bit subvectors
3903 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3904   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3905   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3906     return false;
3907   // The index should be aligned on a vecWidth-bit boundary.
3908   uint64_t Index =
3909     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3910
3911   MVT VT = N->getSimpleValueType(0);
3912   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3913   bool Result = (Index * ElSize) % vecWidth == 0;
3914
3915   return Result;
3916 }
3917
3918 bool X86::isVINSERT128Index(SDNode *N) {
3919   return isVINSERTIndex(N, 128);
3920 }
3921
3922 bool X86::isVINSERT256Index(SDNode *N) {
3923   return isVINSERTIndex(N, 256);
3924 }
3925
3926 bool X86::isVEXTRACT128Index(SDNode *N) {
3927   return isVEXTRACTIndex(N, 128);
3928 }
3929
3930 bool X86::isVEXTRACT256Index(SDNode *N) {
3931   return isVEXTRACTIndex(N, 256);
3932 }
3933
3934 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3935   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3936   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3937     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3938
3939   uint64_t Index =
3940     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3941
3942   MVT VecVT = N->getOperand(0).getSimpleValueType();
3943   MVT ElVT = VecVT.getVectorElementType();
3944
3945   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3946   return Index / NumElemsPerChunk;
3947 }
3948
3949 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3950   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3951   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3952     llvm_unreachable("Illegal insert subvector for VINSERT");
3953
3954   uint64_t Index =
3955     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3956
3957   MVT VecVT = N->getSimpleValueType(0);
3958   MVT ElVT = VecVT.getVectorElementType();
3959
3960   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3961   return Index / NumElemsPerChunk;
3962 }
3963
3964 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3965 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3966 /// and VINSERTI128 instructions.
3967 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3968   return getExtractVEXTRACTImmediate(N, 128);
3969 }
3970
3971 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3972 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3973 /// and VINSERTI64x4 instructions.
3974 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3975   return getExtractVEXTRACTImmediate(N, 256);
3976 }
3977
3978 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3979 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3980 /// and VINSERTI128 instructions.
3981 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3982   return getInsertVINSERTImmediate(N, 128);
3983 }
3984
3985 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3986 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3987 /// and VINSERTI64x4 instructions.
3988 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3989   return getInsertVINSERTImmediate(N, 256);
3990 }
3991
3992 /// isZero - Returns true if Elt is a constant integer zero
3993 static bool isZero(SDValue V) {
3994   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3995   return C && C->isNullValue();
3996 }
3997
3998 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3999 /// constant +0.0.
4000 bool X86::isZeroNode(SDValue Elt) {
4001   if (isZero(Elt))
4002     return true;
4003   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4004     return CFP->getValueAPF().isPosZero();
4005   return false;
4006 }
4007
4008 /// getZeroVector - Returns a vector of specified type with all zero elements.
4009 ///
4010 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4011                              SelectionDAG &DAG, SDLoc dl) {
4012   assert(VT.isVector() && "Expected a vector type");
4013
4014   // Always build SSE zero vectors as <4 x i32> bitcasted
4015   // to their dest type. This ensures they get CSE'd.
4016   SDValue Vec;
4017   if (VT.is128BitVector()) {  // SSE
4018     if (Subtarget->hasSSE2()) {  // SSE2
4019       SDValue Cst = DAG.getConstant(0, MVT::i32);
4020       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4021     } else { // SSE1
4022       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4023       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4024     }
4025   } else if (VT.is256BitVector()) { // AVX
4026     if (Subtarget->hasInt256()) { // AVX2
4027       SDValue Cst = DAG.getConstant(0, MVT::i32);
4028       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4029       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4030     } else {
4031       // 256-bit logic and arithmetic instructions in AVX are all
4032       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4033       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4034       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4035       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4036     }
4037   } else if (VT.is512BitVector()) { // AVX-512
4038       SDValue Cst = DAG.getConstant(0, MVT::i32);
4039       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4040                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4041       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4042   } else if (VT.getScalarType() == MVT::i1) {
4043
4044     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4045             && "Unexpected vector type");
4046     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4047             && "Unexpected vector type");
4048     SDValue Cst = DAG.getConstant(0, MVT::i1);
4049     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4050     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4051   } else
4052     llvm_unreachable("Unexpected vector type");
4053
4054   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4055 }
4056
4057 /// getOnesVector - Returns a vector of specified type with all bits set.
4058 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4059 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4060 /// Then bitcast to their original type, ensuring they get CSE'd.
4061 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4062                              SDLoc dl) {
4063   assert(VT.isVector() && "Expected a vector type");
4064
4065   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4066   SDValue Vec;
4067   if (VT.is256BitVector()) {
4068     if (HasInt256) { // AVX2
4069       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4070       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4071     } else { // AVX
4072       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4073       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4074     }
4075   } else if (VT.is128BitVector()) {
4076     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4077   } else
4078     llvm_unreachable("Unexpected vector type");
4079
4080   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4081 }
4082
4083 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4084 /// operation of specified width.
4085 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4086                        SDValue V2) {
4087   unsigned NumElems = VT.getVectorNumElements();
4088   SmallVector<int, 8> Mask;
4089   Mask.push_back(NumElems);
4090   for (unsigned i = 1; i != NumElems; ++i)
4091     Mask.push_back(i);
4092   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4093 }
4094
4095 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4096 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4097                           SDValue V2) {
4098   unsigned NumElems = VT.getVectorNumElements();
4099   SmallVector<int, 8> Mask;
4100   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4101     Mask.push_back(i);
4102     Mask.push_back(i + NumElems);
4103   }
4104   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4105 }
4106
4107 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4108 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4109                           SDValue V2) {
4110   unsigned NumElems = VT.getVectorNumElements();
4111   SmallVector<int, 8> Mask;
4112   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4113     Mask.push_back(i + Half);
4114     Mask.push_back(i + NumElems + Half);
4115   }
4116   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4117 }
4118
4119 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4120 /// vector of zero or undef vector.  This produces a shuffle where the low
4121 /// element of V2 is swizzled into the zero/undef vector, landing at element
4122 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4123 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4124                                            bool IsZero,
4125                                            const X86Subtarget *Subtarget,
4126                                            SelectionDAG &DAG) {
4127   MVT VT = V2.getSimpleValueType();
4128   SDValue V1 = IsZero
4129     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4130   unsigned NumElems = VT.getVectorNumElements();
4131   SmallVector<int, 16> MaskVec;
4132   for (unsigned i = 0; i != NumElems; ++i)
4133     // If this is the insertion idx, put the low elt of V2 here.
4134     MaskVec.push_back(i == Idx ? NumElems : i);
4135   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4136 }
4137
4138 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4139 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4140 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4141 /// shuffles which use a single input multiple times, and in those cases it will
4142 /// adjust the mask to only have indices within that single input.
4143 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4144                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4145   unsigned NumElems = VT.getVectorNumElements();
4146   SDValue ImmN;
4147
4148   IsUnary = false;
4149   bool IsFakeUnary = false;
4150   switch(N->getOpcode()) {
4151   case X86ISD::BLENDI:
4152     ImmN = N->getOperand(N->getNumOperands()-1);
4153     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4154     break;
4155   case X86ISD::SHUFP:
4156     ImmN = N->getOperand(N->getNumOperands()-1);
4157     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4158     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4159     break;
4160   case X86ISD::UNPCKH:
4161     DecodeUNPCKHMask(VT, Mask);
4162     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4163     break;
4164   case X86ISD::UNPCKL:
4165     DecodeUNPCKLMask(VT, Mask);
4166     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4167     break;
4168   case X86ISD::MOVHLPS:
4169     DecodeMOVHLPSMask(NumElems, Mask);
4170     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4171     break;
4172   case X86ISD::MOVLHPS:
4173     DecodeMOVLHPSMask(NumElems, Mask);
4174     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4175     break;
4176   case X86ISD::PALIGNR:
4177     ImmN = N->getOperand(N->getNumOperands()-1);
4178     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4179     break;
4180   case X86ISD::PSHUFD:
4181   case X86ISD::VPERMILPI:
4182     ImmN = N->getOperand(N->getNumOperands()-1);
4183     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4184     IsUnary = true;
4185     break;
4186   case X86ISD::PSHUFHW:
4187     ImmN = N->getOperand(N->getNumOperands()-1);
4188     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4189     IsUnary = true;
4190     break;
4191   case X86ISD::PSHUFLW:
4192     ImmN = N->getOperand(N->getNumOperands()-1);
4193     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4194     IsUnary = true;
4195     break;
4196   case X86ISD::PSHUFB: {
4197     IsUnary = true;
4198     SDValue MaskNode = N->getOperand(1);
4199     while (MaskNode->getOpcode() == ISD::BITCAST)
4200       MaskNode = MaskNode->getOperand(0);
4201
4202     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4203       // If we have a build-vector, then things are easy.
4204       EVT VT = MaskNode.getValueType();
4205       assert(VT.isVector() &&
4206              "Can't produce a non-vector with a build_vector!");
4207       if (!VT.isInteger())
4208         return false;
4209
4210       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4211
4212       SmallVector<uint64_t, 32> RawMask;
4213       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4214         SDValue Op = MaskNode->getOperand(i);
4215         if (Op->getOpcode() == ISD::UNDEF) {
4216           RawMask.push_back((uint64_t)SM_SentinelUndef);
4217           continue;
4218         }
4219         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4220         if (!CN)
4221           return false;
4222         APInt MaskElement = CN->getAPIntValue();
4223
4224         // We now have to decode the element which could be any integer size and
4225         // extract each byte of it.
4226         for (int j = 0; j < NumBytesPerElement; ++j) {
4227           // Note that this is x86 and so always little endian: the low byte is
4228           // the first byte of the mask.
4229           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4230           MaskElement = MaskElement.lshr(8);
4231         }
4232       }
4233       DecodePSHUFBMask(RawMask, Mask);
4234       break;
4235     }
4236
4237     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4238     if (!MaskLoad)
4239       return false;
4240
4241     SDValue Ptr = MaskLoad->getBasePtr();
4242     if (Ptr->getOpcode() == X86ISD::Wrapper)
4243       Ptr = Ptr->getOperand(0);
4244
4245     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4246     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4247       return false;
4248
4249     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4250       DecodePSHUFBMask(C, Mask);
4251       if (Mask.empty())
4252         return false;
4253       break;
4254     }
4255
4256     return false;
4257   }
4258   case X86ISD::VPERMI:
4259     ImmN = N->getOperand(N->getNumOperands()-1);
4260     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4261     IsUnary = true;
4262     break;
4263   case X86ISD::MOVSS:
4264   case X86ISD::MOVSD:
4265     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4266     break;
4267   case X86ISD::VPERM2X128:
4268     ImmN = N->getOperand(N->getNumOperands()-1);
4269     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4270     if (Mask.empty()) return false;
4271     break;
4272   case X86ISD::MOVSLDUP:
4273     DecodeMOVSLDUPMask(VT, Mask);
4274     IsUnary = true;
4275     break;
4276   case X86ISD::MOVSHDUP:
4277     DecodeMOVSHDUPMask(VT, Mask);
4278     IsUnary = true;
4279     break;
4280   case X86ISD::MOVDDUP:
4281     DecodeMOVDDUPMask(VT, Mask);
4282     IsUnary = true;
4283     break;
4284   case X86ISD::MOVLHPD:
4285   case X86ISD::MOVLPD:
4286   case X86ISD::MOVLPS:
4287     // Not yet implemented
4288     return false;
4289   default: llvm_unreachable("unknown target shuffle node");
4290   }
4291
4292   // If we have a fake unary shuffle, the shuffle mask is spread across two
4293   // inputs that are actually the same node. Re-map the mask to always point
4294   // into the first input.
4295   if (IsFakeUnary)
4296     for (int &M : Mask)
4297       if (M >= (int)Mask.size())
4298         M -= Mask.size();
4299
4300   return true;
4301 }
4302
4303 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4304 /// element of the result of the vector shuffle.
4305 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4306                                    unsigned Depth) {
4307   if (Depth == 6)
4308     return SDValue();  // Limit search depth.
4309
4310   SDValue V = SDValue(N, 0);
4311   EVT VT = V.getValueType();
4312   unsigned Opcode = V.getOpcode();
4313
4314   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4315   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4316     int Elt = SV->getMaskElt(Index);
4317
4318     if (Elt < 0)
4319       return DAG.getUNDEF(VT.getVectorElementType());
4320
4321     unsigned NumElems = VT.getVectorNumElements();
4322     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4323                                          : SV->getOperand(1);
4324     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4325   }
4326
4327   // Recurse into target specific vector shuffles to find scalars.
4328   if (isTargetShuffle(Opcode)) {
4329     MVT ShufVT = V.getSimpleValueType();
4330     unsigned NumElems = ShufVT.getVectorNumElements();
4331     SmallVector<int, 16> ShuffleMask;
4332     bool IsUnary;
4333
4334     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4335       return SDValue();
4336
4337     int Elt = ShuffleMask[Index];
4338     if (Elt < 0)
4339       return DAG.getUNDEF(ShufVT.getVectorElementType());
4340
4341     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4342                                          : N->getOperand(1);
4343     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4344                                Depth+1);
4345   }
4346
4347   // Actual nodes that may contain scalar elements
4348   if (Opcode == ISD::BITCAST) {
4349     V = V.getOperand(0);
4350     EVT SrcVT = V.getValueType();
4351     unsigned NumElems = VT.getVectorNumElements();
4352
4353     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4354       return SDValue();
4355   }
4356
4357   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4358     return (Index == 0) ? V.getOperand(0)
4359                         : DAG.getUNDEF(VT.getVectorElementType());
4360
4361   if (V.getOpcode() == ISD::BUILD_VECTOR)
4362     return V.getOperand(Index);
4363
4364   return SDValue();
4365 }
4366
4367 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4368 ///
4369 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4370                                        unsigned NumNonZero, unsigned NumZero,
4371                                        SelectionDAG &DAG,
4372                                        const X86Subtarget* Subtarget,
4373                                        const TargetLowering &TLI) {
4374   if (NumNonZero > 8)
4375     return SDValue();
4376
4377   SDLoc dl(Op);
4378   SDValue V;
4379   bool First = true;
4380   for (unsigned i = 0; i < 16; ++i) {
4381     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4382     if (ThisIsNonZero && First) {
4383       if (NumZero)
4384         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4385       else
4386         V = DAG.getUNDEF(MVT::v8i16);
4387       First = false;
4388     }
4389
4390     if ((i & 1) != 0) {
4391       SDValue ThisElt, LastElt;
4392       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4393       if (LastIsNonZero) {
4394         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4395                               MVT::i16, Op.getOperand(i-1));
4396       }
4397       if (ThisIsNonZero) {
4398         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4399         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4400                               ThisElt, DAG.getConstant(8, MVT::i8));
4401         if (LastIsNonZero)
4402           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4403       } else
4404         ThisElt = LastElt;
4405
4406       if (ThisElt.getNode())
4407         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4408                         DAG.getIntPtrConstant(i/2));
4409     }
4410   }
4411
4412   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4413 }
4414
4415 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4416 ///
4417 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4418                                      unsigned NumNonZero, unsigned NumZero,
4419                                      SelectionDAG &DAG,
4420                                      const X86Subtarget* Subtarget,
4421                                      const TargetLowering &TLI) {
4422   if (NumNonZero > 4)
4423     return SDValue();
4424
4425   SDLoc dl(Op);
4426   SDValue V;
4427   bool First = true;
4428   for (unsigned i = 0; i < 8; ++i) {
4429     bool isNonZero = (NonZeros & (1 << i)) != 0;
4430     if (isNonZero) {
4431       if (First) {
4432         if (NumZero)
4433           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4434         else
4435           V = DAG.getUNDEF(MVT::v8i16);
4436         First = false;
4437       }
4438       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4439                       MVT::v8i16, V, Op.getOperand(i),
4440                       DAG.getIntPtrConstant(i));
4441     }
4442   }
4443
4444   return V;
4445 }
4446
4447 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4448 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4449                                      const X86Subtarget *Subtarget,
4450                                      const TargetLowering &TLI) {
4451   // Find all zeroable elements.
4452   std::bitset<4> Zeroable;
4453   for (int i=0; i < 4; ++i) {
4454     SDValue Elt = Op->getOperand(i);
4455     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4456   }
4457   assert(Zeroable.size() - Zeroable.count() > 1 &&
4458          "We expect at least two non-zero elements!");
4459
4460   // We only know how to deal with build_vector nodes where elements are either
4461   // zeroable or extract_vector_elt with constant index.
4462   SDValue FirstNonZero;
4463   unsigned FirstNonZeroIdx;
4464   for (unsigned i=0; i < 4; ++i) {
4465     if (Zeroable[i])
4466       continue;
4467     SDValue Elt = Op->getOperand(i);
4468     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4469         !isa<ConstantSDNode>(Elt.getOperand(1)))
4470       return SDValue();
4471     // Make sure that this node is extracting from a 128-bit vector.
4472     MVT VT = Elt.getOperand(0).getSimpleValueType();
4473     if (!VT.is128BitVector())
4474       return SDValue();
4475     if (!FirstNonZero.getNode()) {
4476       FirstNonZero = Elt;
4477       FirstNonZeroIdx = i;
4478     }
4479   }
4480
4481   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4482   SDValue V1 = FirstNonZero.getOperand(0);
4483   MVT VT = V1.getSimpleValueType();
4484
4485   // See if this build_vector can be lowered as a blend with zero.
4486   SDValue Elt;
4487   unsigned EltMaskIdx, EltIdx;
4488   int Mask[4];
4489   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4490     if (Zeroable[EltIdx]) {
4491       // The zero vector will be on the right hand side.
4492       Mask[EltIdx] = EltIdx+4;
4493       continue;
4494     }
4495
4496     Elt = Op->getOperand(EltIdx);
4497     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4498     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4499     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4500       break;
4501     Mask[EltIdx] = EltIdx;
4502   }
4503
4504   if (EltIdx == 4) {
4505     // Let the shuffle legalizer deal with blend operations.
4506     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4507     if (V1.getSimpleValueType() != VT)
4508       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4509     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4510   }
4511
4512   // See if we can lower this build_vector to a INSERTPS.
4513   if (!Subtarget->hasSSE41())
4514     return SDValue();
4515
4516   SDValue V2 = Elt.getOperand(0);
4517   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4518     V1 = SDValue();
4519
4520   bool CanFold = true;
4521   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4522     if (Zeroable[i])
4523       continue;
4524
4525     SDValue Current = Op->getOperand(i);
4526     SDValue SrcVector = Current->getOperand(0);
4527     if (!V1.getNode())
4528       V1 = SrcVector;
4529     CanFold = SrcVector == V1 &&
4530       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4531   }
4532
4533   if (!CanFold)
4534     return SDValue();
4535
4536   assert(V1.getNode() && "Expected at least two non-zero elements!");
4537   if (V1.getSimpleValueType() != MVT::v4f32)
4538     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4539   if (V2.getSimpleValueType() != MVT::v4f32)
4540     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4541
4542   // Ok, we can emit an INSERTPS instruction.
4543   unsigned ZMask = Zeroable.to_ulong();
4544
4545   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4546   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4547   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4548                                DAG.getIntPtrConstant(InsertPSMask));
4549   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4550 }
4551
4552 /// Return a vector logical shift node.
4553 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4554                          unsigned NumBits, SelectionDAG &DAG,
4555                          const TargetLowering &TLI, SDLoc dl) {
4556   assert(VT.is128BitVector() && "Unknown type for VShift");
4557   MVT ShVT = MVT::v2i64;
4558   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4559   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4560   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4561   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4562   SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4563   return DAG.getNode(ISD::BITCAST, dl, VT,
4564                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4565 }
4566
4567 static SDValue
4568 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4569
4570   // Check if the scalar load can be widened into a vector load. And if
4571   // the address is "base + cst" see if the cst can be "absorbed" into
4572   // the shuffle mask.
4573   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4574     SDValue Ptr = LD->getBasePtr();
4575     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4576       return SDValue();
4577     EVT PVT = LD->getValueType(0);
4578     if (PVT != MVT::i32 && PVT != MVT::f32)
4579       return SDValue();
4580
4581     int FI = -1;
4582     int64_t Offset = 0;
4583     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4584       FI = FINode->getIndex();
4585       Offset = 0;
4586     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4587                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4588       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4589       Offset = Ptr.getConstantOperandVal(1);
4590       Ptr = Ptr.getOperand(0);
4591     } else {
4592       return SDValue();
4593     }
4594
4595     // FIXME: 256-bit vector instructions don't require a strict alignment,
4596     // improve this code to support it better.
4597     unsigned RequiredAlign = VT.getSizeInBits()/8;
4598     SDValue Chain = LD->getChain();
4599     // Make sure the stack object alignment is at least 16 or 32.
4600     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4601     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4602       if (MFI->isFixedObjectIndex(FI)) {
4603         // Can't change the alignment. FIXME: It's possible to compute
4604         // the exact stack offset and reference FI + adjust offset instead.
4605         // If someone *really* cares about this. That's the way to implement it.
4606         return SDValue();
4607       } else {
4608         MFI->setObjectAlignment(FI, RequiredAlign);
4609       }
4610     }
4611
4612     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4613     // Ptr + (Offset & ~15).
4614     if (Offset < 0)
4615       return SDValue();
4616     if ((Offset % RequiredAlign) & 3)
4617       return SDValue();
4618     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4619     if (StartOffset)
4620       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4621                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4622
4623     int EltNo = (Offset - StartOffset) >> 2;
4624     unsigned NumElems = VT.getVectorNumElements();
4625
4626     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4627     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4628                              LD->getPointerInfo().getWithOffset(StartOffset),
4629                              false, false, false, 0);
4630
4631     SmallVector<int, 8> Mask(NumElems, EltNo);
4632
4633     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4634   }
4635
4636   return SDValue();
4637 }
4638
4639 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4640 /// elements can be replaced by a single large load which has the same value as
4641 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4642 ///
4643 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4644 ///
4645 /// FIXME: we'd also like to handle the case where the last elements are zero
4646 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4647 /// There's even a handy isZeroNode for that purpose.
4648 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4649                                         SDLoc &DL, SelectionDAG &DAG,
4650                                         bool isAfterLegalize) {
4651   unsigned NumElems = Elts.size();
4652
4653   LoadSDNode *LDBase = nullptr;
4654   unsigned LastLoadedElt = -1U;
4655
4656   // For each element in the initializer, see if we've found a load or an undef.
4657   // If we don't find an initial load element, or later load elements are
4658   // non-consecutive, bail out.
4659   for (unsigned i = 0; i < NumElems; ++i) {
4660     SDValue Elt = Elts[i];
4661     // Look through a bitcast.
4662     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4663       Elt = Elt.getOperand(0);
4664     if (!Elt.getNode() ||
4665         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4666       return SDValue();
4667     if (!LDBase) {
4668       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4669         return SDValue();
4670       LDBase = cast<LoadSDNode>(Elt.getNode());
4671       LastLoadedElt = i;
4672       continue;
4673     }
4674     if (Elt.getOpcode() == ISD::UNDEF)
4675       continue;
4676
4677     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4678     EVT LdVT = Elt.getValueType();
4679     // Each loaded element must be the correct fractional portion of the
4680     // requested vector load.
4681     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4682       return SDValue();
4683     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4684       return SDValue();
4685     LastLoadedElt = i;
4686   }
4687
4688   // If we have found an entire vector of loads and undefs, then return a large
4689   // load of the entire vector width starting at the base pointer.  If we found
4690   // consecutive loads for the low half, generate a vzext_load node.
4691   if (LastLoadedElt == NumElems - 1) {
4692     assert(LDBase && "Did not find base load for merging consecutive loads");
4693     EVT EltVT = LDBase->getValueType(0);
4694     // Ensure that the input vector size for the merged loads matches the
4695     // cumulative size of the input elements.
4696     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4697       return SDValue();
4698
4699     if (isAfterLegalize &&
4700         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4701       return SDValue();
4702
4703     SDValue NewLd = SDValue();
4704
4705     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4706                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4707                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4708                         LDBase->getAlignment());
4709
4710     if (LDBase->hasAnyUseOfValue(1)) {
4711       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4712                                      SDValue(LDBase, 1),
4713                                      SDValue(NewLd.getNode(), 1));
4714       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4715       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4716                              SDValue(NewLd.getNode(), 1));
4717     }
4718
4719     return NewLd;
4720   }
4721
4722   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4723   //of a v4i32 / v4f32. It's probably worth generalizing.
4724   EVT EltVT = VT.getVectorElementType();
4725   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4726       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4727     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4728     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4729     SDValue ResNode =
4730         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4731                                 LDBase->getPointerInfo(),
4732                                 LDBase->getAlignment(),
4733                                 false/*isVolatile*/, true/*ReadMem*/,
4734                                 false/*WriteMem*/);
4735
4736     // Make sure the newly-created LOAD is in the same position as LDBase in
4737     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4738     // update uses of LDBase's output chain to use the TokenFactor.
4739     if (LDBase->hasAnyUseOfValue(1)) {
4740       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4741                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4742       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4743       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4744                              SDValue(ResNode.getNode(), 1));
4745     }
4746
4747     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4748   }
4749   return SDValue();
4750 }
4751
4752 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4753 /// to generate a splat value for the following cases:
4754 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4755 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4756 /// a scalar load, or a constant.
4757 /// The VBROADCAST node is returned when a pattern is found,
4758 /// or SDValue() otherwise.
4759 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4760                                     SelectionDAG &DAG) {
4761   // VBROADCAST requires AVX.
4762   // TODO: Splats could be generated for non-AVX CPUs using SSE
4763   // instructions, but there's less potential gain for only 128-bit vectors.
4764   if (!Subtarget->hasAVX())
4765     return SDValue();
4766
4767   MVT VT = Op.getSimpleValueType();
4768   SDLoc dl(Op);
4769
4770   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4771          "Unsupported vector type for broadcast.");
4772
4773   SDValue Ld;
4774   bool ConstSplatVal;
4775
4776   switch (Op.getOpcode()) {
4777     default:
4778       // Unknown pattern found.
4779       return SDValue();
4780
4781     case ISD::BUILD_VECTOR: {
4782       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4783       BitVector UndefElements;
4784       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4785
4786       // We need a splat of a single value to use broadcast, and it doesn't
4787       // make any sense if the value is only in one element of the vector.
4788       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4789         return SDValue();
4790
4791       Ld = Splat;
4792       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4793                        Ld.getOpcode() == ISD::ConstantFP);
4794
4795       // Make sure that all of the users of a non-constant load are from the
4796       // BUILD_VECTOR node.
4797       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4798         return SDValue();
4799       break;
4800     }
4801
4802     case ISD::VECTOR_SHUFFLE: {
4803       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4804
4805       // Shuffles must have a splat mask where the first element is
4806       // broadcasted.
4807       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4808         return SDValue();
4809
4810       SDValue Sc = Op.getOperand(0);
4811       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4812           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4813
4814         if (!Subtarget->hasInt256())
4815           return SDValue();
4816
4817         // Use the register form of the broadcast instruction available on AVX2.
4818         if (VT.getSizeInBits() >= 256)
4819           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4820         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4821       }
4822
4823       Ld = Sc.getOperand(0);
4824       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4825                        Ld.getOpcode() == ISD::ConstantFP);
4826
4827       // The scalar_to_vector node and the suspected
4828       // load node must have exactly one user.
4829       // Constants may have multiple users.
4830
4831       // AVX-512 has register version of the broadcast
4832       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4833         Ld.getValueType().getSizeInBits() >= 32;
4834       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4835           !hasRegVer))
4836         return SDValue();
4837       break;
4838     }
4839   }
4840
4841   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4842   bool IsGE256 = (VT.getSizeInBits() >= 256);
4843
4844   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4845   // instruction to save 8 or more bytes of constant pool data.
4846   // TODO: If multiple splats are generated to load the same constant,
4847   // it may be detrimental to overall size. There needs to be a way to detect
4848   // that condition to know if this is truly a size win.
4849   const Function *F = DAG.getMachineFunction().getFunction();
4850   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4851
4852   // Handle broadcasting a single constant scalar from the constant pool
4853   // into a vector.
4854   // On Sandybridge (no AVX2), it is still better to load a constant vector
4855   // from the constant pool and not to broadcast it from a scalar.
4856   // But override that restriction when optimizing for size.
4857   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4858   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4859     EVT CVT = Ld.getValueType();
4860     assert(!CVT.isVector() && "Must not broadcast a vector type");
4861
4862     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4863     // For size optimization, also splat v2f64 and v2i64, and for size opt
4864     // with AVX2, also splat i8 and i16.
4865     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4866     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4867         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4868       const Constant *C = nullptr;
4869       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4870         C = CI->getConstantIntValue();
4871       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4872         C = CF->getConstantFPValue();
4873
4874       assert(C && "Invalid constant type");
4875
4876       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4877       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4878       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4879       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4880                        MachinePointerInfo::getConstantPool(),
4881                        false, false, false, Alignment);
4882
4883       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4884     }
4885   }
4886
4887   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4888
4889   // Handle AVX2 in-register broadcasts.
4890   if (!IsLoad && Subtarget->hasInt256() &&
4891       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4892     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4893
4894   // The scalar source must be a normal load.
4895   if (!IsLoad)
4896     return SDValue();
4897
4898   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4899       (Subtarget->hasVLX() && ScalarSize == 64))
4900     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4901
4902   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4903   // double since there is no vbroadcastsd xmm
4904   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4905     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4906       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4907   }
4908
4909   // Unsupported broadcast.
4910   return SDValue();
4911 }
4912
4913 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4914 /// underlying vector and index.
4915 ///
4916 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4917 /// index.
4918 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4919                                          SDValue ExtIdx) {
4920   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4921   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4922     return Idx;
4923
4924   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4925   // lowered this:
4926   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4927   // to:
4928   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
4929   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
4930   //                           undef)
4931   //                       Constant<0>)
4932   // In this case the vector is the extract_subvector expression and the index
4933   // is 2, as specified by the shuffle.
4934   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4935   SDValue ShuffleVec = SVOp->getOperand(0);
4936   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4937   assert(ShuffleVecVT.getVectorElementType() ==
4938          ExtractedFromVec.getSimpleValueType().getVectorElementType());
4939
4940   int ShuffleIdx = SVOp->getMaskElt(Idx);
4941   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4942     ExtractedFromVec = ShuffleVec;
4943     return ShuffleIdx;
4944   }
4945   return Idx;
4946 }
4947
4948 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4949   MVT VT = Op.getSimpleValueType();
4950
4951   // Skip if insert_vec_elt is not supported.
4952   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4953   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
4954     return SDValue();
4955
4956   SDLoc DL(Op);
4957   unsigned NumElems = Op.getNumOperands();
4958
4959   SDValue VecIn1;
4960   SDValue VecIn2;
4961   SmallVector<unsigned, 4> InsertIndices;
4962   SmallVector<int, 8> Mask(NumElems, -1);
4963
4964   for (unsigned i = 0; i != NumElems; ++i) {
4965     unsigned Opc = Op.getOperand(i).getOpcode();
4966
4967     if (Opc == ISD::UNDEF)
4968       continue;
4969
4970     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
4971       // Quit if more than 1 elements need inserting.
4972       if (InsertIndices.size() > 1)
4973         return SDValue();
4974
4975       InsertIndices.push_back(i);
4976       continue;
4977     }
4978
4979     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
4980     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
4981     // Quit if non-constant index.
4982     if (!isa<ConstantSDNode>(ExtIdx))
4983       return SDValue();
4984     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
4985
4986     // Quit if extracted from vector of different type.
4987     if (ExtractedFromVec.getValueType() != VT)
4988       return SDValue();
4989
4990     if (!VecIn1.getNode())
4991       VecIn1 = ExtractedFromVec;
4992     else if (VecIn1 != ExtractedFromVec) {
4993       if (!VecIn2.getNode())
4994         VecIn2 = ExtractedFromVec;
4995       else if (VecIn2 != ExtractedFromVec)
4996         // Quit if more than 2 vectors to shuffle
4997         return SDValue();
4998     }
4999
5000     if (ExtractedFromVec == VecIn1)
5001       Mask[i] = Idx;
5002     else if (ExtractedFromVec == VecIn2)
5003       Mask[i] = Idx + NumElems;
5004   }
5005
5006   if (!VecIn1.getNode())
5007     return SDValue();
5008
5009   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5010   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5011   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5012     unsigned Idx = InsertIndices[i];
5013     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5014                      DAG.getIntPtrConstant(Idx));
5015   }
5016
5017   return NV;
5018 }
5019
5020 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5021 SDValue
5022 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5023
5024   MVT VT = Op.getSimpleValueType();
5025   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5026          "Unexpected type in LowerBUILD_VECTORvXi1!");
5027
5028   SDLoc dl(Op);
5029   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5030     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5031     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5032     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5033   }
5034
5035   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5036     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5037     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5038     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5039   }
5040
5041   bool AllContants = true;
5042   uint64_t Immediate = 0;
5043   int NonConstIdx = -1;
5044   bool IsSplat = true;
5045   unsigned NumNonConsts = 0;
5046   unsigned NumConsts = 0;
5047   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5048     SDValue In = Op.getOperand(idx);
5049     if (In.getOpcode() == ISD::UNDEF)
5050       continue;
5051     if (!isa<ConstantSDNode>(In)) {
5052       AllContants = false;
5053       NonConstIdx = idx;
5054       NumNonConsts++;
5055     } else {
5056       NumConsts++;
5057       if (cast<ConstantSDNode>(In)->getZExtValue())
5058       Immediate |= (1ULL << idx);
5059     }
5060     if (In != Op.getOperand(0))
5061       IsSplat = false;
5062   }
5063
5064   if (AllContants) {
5065     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5066       DAG.getConstant(Immediate, MVT::i16));
5067     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5068                        DAG.getIntPtrConstant(0));
5069   }
5070
5071   if (NumNonConsts == 1 && NonConstIdx != 0) {
5072     SDValue DstVec;
5073     if (NumConsts) {
5074       SDValue VecAsImm = DAG.getConstant(Immediate,
5075                                          MVT::getIntegerVT(VT.getSizeInBits()));
5076       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5077     }
5078     else
5079       DstVec = DAG.getUNDEF(VT);
5080     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5081                        Op.getOperand(NonConstIdx),
5082                        DAG.getIntPtrConstant(NonConstIdx));
5083   }
5084   if (!IsSplat && (NonConstIdx != 0))
5085     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5086   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5087   SDValue Select;
5088   if (IsSplat)
5089     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5090                           DAG.getConstant(-1, SelectVT),
5091                           DAG.getConstant(0, SelectVT));
5092   else
5093     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5094                          DAG.getConstant((Immediate | 1), SelectVT),
5095                          DAG.getConstant(Immediate, SelectVT));
5096   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5097 }
5098
5099 /// \brief Return true if \p N implements a horizontal binop and return the
5100 /// operands for the horizontal binop into V0 and V1.
5101 ///
5102 /// This is a helper function of PerformBUILD_VECTORCombine.
5103 /// This function checks that the build_vector \p N in input implements a
5104 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5105 /// operation to match.
5106 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5107 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5108 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5109 /// arithmetic sub.
5110 ///
5111 /// This function only analyzes elements of \p N whose indices are
5112 /// in range [BaseIdx, LastIdx).
5113 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5114                               SelectionDAG &DAG,
5115                               unsigned BaseIdx, unsigned LastIdx,
5116                               SDValue &V0, SDValue &V1) {
5117   EVT VT = N->getValueType(0);
5118
5119   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5120   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5121          "Invalid Vector in input!");
5122
5123   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5124   bool CanFold = true;
5125   unsigned ExpectedVExtractIdx = BaseIdx;
5126   unsigned NumElts = LastIdx - BaseIdx;
5127   V0 = DAG.getUNDEF(VT);
5128   V1 = DAG.getUNDEF(VT);
5129
5130   // Check if N implements a horizontal binop.
5131   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5132     SDValue Op = N->getOperand(i + BaseIdx);
5133
5134     // Skip UNDEFs.
5135     if (Op->getOpcode() == ISD::UNDEF) {
5136       // Update the expected vector extract index.
5137       if (i * 2 == NumElts)
5138         ExpectedVExtractIdx = BaseIdx;
5139       ExpectedVExtractIdx += 2;
5140       continue;
5141     }
5142
5143     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5144
5145     if (!CanFold)
5146       break;
5147
5148     SDValue Op0 = Op.getOperand(0);
5149     SDValue Op1 = Op.getOperand(1);
5150
5151     // Try to match the following pattern:
5152     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5153     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5154         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5155         Op0.getOperand(0) == Op1.getOperand(0) &&
5156         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5157         isa<ConstantSDNode>(Op1.getOperand(1)));
5158     if (!CanFold)
5159       break;
5160
5161     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5162     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5163
5164     if (i * 2 < NumElts) {
5165       if (V0.getOpcode() == ISD::UNDEF)
5166         V0 = Op0.getOperand(0);
5167     } else {
5168       if (V1.getOpcode() == ISD::UNDEF)
5169         V1 = Op0.getOperand(0);
5170       if (i * 2 == NumElts)
5171         ExpectedVExtractIdx = BaseIdx;
5172     }
5173
5174     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5175     if (I0 == ExpectedVExtractIdx)
5176       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5177     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5178       // Try to match the following dag sequence:
5179       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5180       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5181     } else
5182       CanFold = false;
5183
5184     ExpectedVExtractIdx += 2;
5185   }
5186
5187   return CanFold;
5188 }
5189
5190 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5191 /// a concat_vector.
5192 ///
5193 /// This is a helper function of PerformBUILD_VECTORCombine.
5194 /// This function expects two 256-bit vectors called V0 and V1.
5195 /// At first, each vector is split into two separate 128-bit vectors.
5196 /// Then, the resulting 128-bit vectors are used to implement two
5197 /// horizontal binary operations.
5198 ///
5199 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5200 ///
5201 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5202 /// the two new horizontal binop.
5203 /// When Mode is set, the first horizontal binop dag node would take as input
5204 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5205 /// horizontal binop dag node would take as input the lower 128-bit of V1
5206 /// and the upper 128-bit of V1.
5207 ///   Example:
5208 ///     HADD V0_LO, V0_HI
5209 ///     HADD V1_LO, V1_HI
5210 ///
5211 /// Otherwise, the first horizontal binop dag node takes as input the lower
5212 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5213 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5214 ///   Example:
5215 ///     HADD V0_LO, V1_LO
5216 ///     HADD V0_HI, V1_HI
5217 ///
5218 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5219 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5220 /// the upper 128-bits of the result.
5221 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5222                                      SDLoc DL, SelectionDAG &DAG,
5223                                      unsigned X86Opcode, bool Mode,
5224                                      bool isUndefLO, bool isUndefHI) {
5225   EVT VT = V0.getValueType();
5226   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5227          "Invalid nodes in input!");
5228
5229   unsigned NumElts = VT.getVectorNumElements();
5230   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5231   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5232   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5233   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5234   EVT NewVT = V0_LO.getValueType();
5235
5236   SDValue LO = DAG.getUNDEF(NewVT);
5237   SDValue HI = DAG.getUNDEF(NewVT);
5238
5239   if (Mode) {
5240     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5241     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5242       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5243     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5244       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5245   } else {
5246     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5247     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5248                        V1_LO->getOpcode() != ISD::UNDEF))
5249       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5250
5251     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5252                        V1_HI->getOpcode() != ISD::UNDEF))
5253       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5254   }
5255
5256   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5257 }
5258
5259 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5260 /// sequence of 'vadd + vsub + blendi'.
5261 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5262                            const X86Subtarget *Subtarget) {
5263   SDLoc DL(BV);
5264   EVT VT = BV->getValueType(0);
5265   unsigned NumElts = VT.getVectorNumElements();
5266   SDValue InVec0 = DAG.getUNDEF(VT);
5267   SDValue InVec1 = DAG.getUNDEF(VT);
5268
5269   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5270           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5271
5272   // Odd-numbered elements in the input build vector are obtained from
5273   // adding two integer/float elements.
5274   // Even-numbered elements in the input build vector are obtained from
5275   // subtracting two integer/float elements.
5276   unsigned ExpectedOpcode = ISD::FSUB;
5277   unsigned NextExpectedOpcode = ISD::FADD;
5278   bool AddFound = false;
5279   bool SubFound = false;
5280
5281   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5282     SDValue Op = BV->getOperand(i);
5283
5284     // Skip 'undef' values.
5285     unsigned Opcode = Op.getOpcode();
5286     if (Opcode == ISD::UNDEF) {
5287       std::swap(ExpectedOpcode, NextExpectedOpcode);
5288       continue;
5289     }
5290
5291     // Early exit if we found an unexpected opcode.
5292     if (Opcode != ExpectedOpcode)
5293       return SDValue();
5294
5295     SDValue Op0 = Op.getOperand(0);
5296     SDValue Op1 = Op.getOperand(1);
5297
5298     // Try to match the following pattern:
5299     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5300     // Early exit if we cannot match that sequence.
5301     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5302         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5303         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5304         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5305         Op0.getOperand(1) != Op1.getOperand(1))
5306       return SDValue();
5307
5308     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5309     if (I0 != i)
5310       return SDValue();
5311
5312     // We found a valid add/sub node. Update the information accordingly.
5313     if (i & 1)
5314       AddFound = true;
5315     else
5316       SubFound = true;
5317
5318     // Update InVec0 and InVec1.
5319     if (InVec0.getOpcode() == ISD::UNDEF)
5320       InVec0 = Op0.getOperand(0);
5321     if (InVec1.getOpcode() == ISD::UNDEF)
5322       InVec1 = Op1.getOperand(0);
5323
5324     // Make sure that operands in input to each add/sub node always
5325     // come from a same pair of vectors.
5326     if (InVec0 != Op0.getOperand(0)) {
5327       if (ExpectedOpcode == ISD::FSUB)
5328         return SDValue();
5329
5330       // FADD is commutable. Try to commute the operands
5331       // and then test again.
5332       std::swap(Op0, Op1);
5333       if (InVec0 != Op0.getOperand(0))
5334         return SDValue();
5335     }
5336
5337     if (InVec1 != Op1.getOperand(0))
5338       return SDValue();
5339
5340     // Update the pair of expected opcodes.
5341     std::swap(ExpectedOpcode, NextExpectedOpcode);
5342   }
5343
5344   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5345   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5346       InVec1.getOpcode() != ISD::UNDEF)
5347     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5348
5349   return SDValue();
5350 }
5351
5352 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5353                                           const X86Subtarget *Subtarget) {
5354   SDLoc DL(N);
5355   EVT VT = N->getValueType(0);
5356   unsigned NumElts = VT.getVectorNumElements();
5357   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5358   SDValue InVec0, InVec1;
5359
5360   // Try to match an ADDSUB.
5361   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5362       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5363     SDValue Value = matchAddSub(BV, DAG, Subtarget);
5364     if (Value.getNode())
5365       return Value;
5366   }
5367
5368   // Try to match horizontal ADD/SUB.
5369   unsigned NumUndefsLO = 0;
5370   unsigned NumUndefsHI = 0;
5371   unsigned Half = NumElts/2;
5372
5373   // Count the number of UNDEF operands in the build_vector in input.
5374   for (unsigned i = 0, e = Half; i != e; ++i)
5375     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5376       NumUndefsLO++;
5377
5378   for (unsigned i = Half, e = NumElts; i != e; ++i)
5379     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5380       NumUndefsHI++;
5381
5382   // Early exit if this is either a build_vector of all UNDEFs or all the
5383   // operands but one are UNDEF.
5384   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5385     return SDValue();
5386
5387   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5388     // Try to match an SSE3 float HADD/HSUB.
5389     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5390       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5391
5392     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5393       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5394   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5395     // Try to match an SSSE3 integer HADD/HSUB.
5396     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5397       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5398
5399     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5400       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5401   }
5402
5403   if (!Subtarget->hasAVX())
5404     return SDValue();
5405
5406   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5407     // Try to match an AVX horizontal add/sub of packed single/double
5408     // precision floating point values from 256-bit vectors.
5409     SDValue InVec2, InVec3;
5410     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5411         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5412         ((InVec0.getOpcode() == ISD::UNDEF ||
5413           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5414         ((InVec1.getOpcode() == ISD::UNDEF ||
5415           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5416       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5417
5418     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5419         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5420         ((InVec0.getOpcode() == ISD::UNDEF ||
5421           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5422         ((InVec1.getOpcode() == ISD::UNDEF ||
5423           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5424       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5425   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5426     // Try to match an AVX2 horizontal add/sub of signed integers.
5427     SDValue InVec2, InVec3;
5428     unsigned X86Opcode;
5429     bool CanFold = true;
5430
5431     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5432         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5433         ((InVec0.getOpcode() == ISD::UNDEF ||
5434           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5435         ((InVec1.getOpcode() == ISD::UNDEF ||
5436           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5437       X86Opcode = X86ISD::HADD;
5438     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5439         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5440         ((InVec0.getOpcode() == ISD::UNDEF ||
5441           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5442         ((InVec1.getOpcode() == ISD::UNDEF ||
5443           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5444       X86Opcode = X86ISD::HSUB;
5445     else
5446       CanFold = false;
5447
5448     if (CanFold) {
5449       // Fold this build_vector into a single horizontal add/sub.
5450       // Do this only if the target has AVX2.
5451       if (Subtarget->hasAVX2())
5452         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5453
5454       // Do not try to expand this build_vector into a pair of horizontal
5455       // add/sub if we can emit a pair of scalar add/sub.
5456       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5457         return SDValue();
5458
5459       // Convert this build_vector into a pair of horizontal binop followed by
5460       // a concat vector.
5461       bool isUndefLO = NumUndefsLO == Half;
5462       bool isUndefHI = NumUndefsHI == Half;
5463       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5464                                    isUndefLO, isUndefHI);
5465     }
5466   }
5467
5468   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5469        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5470     unsigned X86Opcode;
5471     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5472       X86Opcode = X86ISD::HADD;
5473     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5474       X86Opcode = X86ISD::HSUB;
5475     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5476       X86Opcode = X86ISD::FHADD;
5477     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5478       X86Opcode = X86ISD::FHSUB;
5479     else
5480       return SDValue();
5481
5482     // Don't try to expand this build_vector into a pair of horizontal add/sub
5483     // if we can simply emit a pair of scalar add/sub.
5484     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5485       return SDValue();
5486
5487     // Convert this build_vector into two horizontal add/sub followed by
5488     // a concat vector.
5489     bool isUndefLO = NumUndefsLO == Half;
5490     bool isUndefHI = NumUndefsHI == Half;
5491     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5492                                  isUndefLO, isUndefHI);
5493   }
5494
5495   return SDValue();
5496 }
5497
5498 SDValue
5499 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5500   SDLoc dl(Op);
5501
5502   MVT VT = Op.getSimpleValueType();
5503   MVT ExtVT = VT.getVectorElementType();
5504   unsigned NumElems = Op.getNumOperands();
5505
5506   // Generate vectors for predicate vectors.
5507   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5508     return LowerBUILD_VECTORvXi1(Op, DAG);
5509
5510   // Vectors containing all zeros can be matched by pxor and xorps later
5511   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5512     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5513     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5514     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5515       return Op;
5516
5517     return getZeroVector(VT, Subtarget, DAG, dl);
5518   }
5519
5520   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5521   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5522   // vpcmpeqd on 256-bit vectors.
5523   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5524     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5525       return Op;
5526
5527     if (!VT.is512BitVector())
5528       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5529   }
5530
5531   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5532   if (Broadcast.getNode())
5533     return Broadcast;
5534
5535   unsigned EVTBits = ExtVT.getSizeInBits();
5536
5537   unsigned NumZero  = 0;
5538   unsigned NumNonZero = 0;
5539   unsigned NonZeros = 0;
5540   bool IsAllConstants = true;
5541   SmallSet<SDValue, 8> Values;
5542   for (unsigned i = 0; i < NumElems; ++i) {
5543     SDValue Elt = Op.getOperand(i);
5544     if (Elt.getOpcode() == ISD::UNDEF)
5545       continue;
5546     Values.insert(Elt);
5547     if (Elt.getOpcode() != ISD::Constant &&
5548         Elt.getOpcode() != ISD::ConstantFP)
5549       IsAllConstants = false;
5550     if (X86::isZeroNode(Elt))
5551       NumZero++;
5552     else {
5553       NonZeros |= (1 << i);
5554       NumNonZero++;
5555     }
5556   }
5557
5558   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5559   if (NumNonZero == 0)
5560     return DAG.getUNDEF(VT);
5561
5562   // Special case for single non-zero, non-undef, element.
5563   if (NumNonZero == 1) {
5564     unsigned Idx = countTrailingZeros(NonZeros);
5565     SDValue Item = Op.getOperand(Idx);
5566
5567     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5568     // the value are obviously zero, truncate the value to i32 and do the
5569     // insertion that way.  Only do this if the value is non-constant or if the
5570     // value is a constant being inserted into element 0.  It is cheaper to do
5571     // a constant pool load than it is to do a movd + shuffle.
5572     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5573         (!IsAllConstants || Idx == 0)) {
5574       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5575         // Handle SSE only.
5576         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5577         EVT VecVT = MVT::v4i32;
5578
5579         // Truncate the value (which may itself be a constant) to i32, and
5580         // convert it to a vector with movd (S2V+shuffle to zero extend).
5581         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5582         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5583         return DAG.getNode(
5584             ISD::BITCAST, dl, VT,
5585             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5586       }
5587     }
5588
5589     // If we have a constant or non-constant insertion into the low element of
5590     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5591     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5592     // depending on what the source datatype is.
5593     if (Idx == 0) {
5594       if (NumZero == 0)
5595         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5596
5597       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5598           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5599         if (VT.is512BitVector()) {
5600           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5601           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5602                              Item, DAG.getIntPtrConstant(0));
5603         }
5604         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5605                "Expected an SSE value type!");
5606         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5607         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5608         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5609       }
5610
5611       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5612         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5613         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5614         if (VT.is256BitVector()) {
5615           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5616           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5617         } else {
5618           assert(VT.is128BitVector() && "Expected an SSE value type!");
5619           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5620         }
5621         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5622       }
5623     }
5624
5625     // Is it a vector logical left shift?
5626     if (NumElems == 2 && Idx == 1 &&
5627         X86::isZeroNode(Op.getOperand(0)) &&
5628         !X86::isZeroNode(Op.getOperand(1))) {
5629       unsigned NumBits = VT.getSizeInBits();
5630       return getVShift(true, VT,
5631                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5632                                    VT, Op.getOperand(1)),
5633                        NumBits/2, DAG, *this, dl);
5634     }
5635
5636     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5637       return SDValue();
5638
5639     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5640     // is a non-constant being inserted into an element other than the low one,
5641     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5642     // movd/movss) to move this into the low element, then shuffle it into
5643     // place.
5644     if (EVTBits == 32) {
5645       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5646       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5647     }
5648   }
5649
5650   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5651   if (Values.size() == 1) {
5652     if (EVTBits == 32) {
5653       // Instead of a shuffle like this:
5654       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5655       // Check if it's possible to issue this instead.
5656       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5657       unsigned Idx = countTrailingZeros(NonZeros);
5658       SDValue Item = Op.getOperand(Idx);
5659       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5660         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5661     }
5662     return SDValue();
5663   }
5664
5665   // A vector full of immediates; various special cases are already
5666   // handled, so this is best done with a single constant-pool load.
5667   if (IsAllConstants)
5668     return SDValue();
5669
5670   // For AVX-length vectors, see if we can use a vector load to get all of the
5671   // elements, otherwise build the individual 128-bit pieces and use
5672   // shuffles to put them in place.
5673   if (VT.is256BitVector() || VT.is512BitVector()) {
5674     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5675
5676     // Check for a build vector of consecutive loads.
5677     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5678       return LD;
5679
5680     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5681
5682     // Build both the lower and upper subvector.
5683     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5684                                 makeArrayRef(&V[0], NumElems/2));
5685     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5686                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5687
5688     // Recreate the wider vector with the lower and upper part.
5689     if (VT.is256BitVector())
5690       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5691     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5692   }
5693
5694   // Let legalizer expand 2-wide build_vectors.
5695   if (EVTBits == 64) {
5696     if (NumNonZero == 1) {
5697       // One half is zero or undef.
5698       unsigned Idx = countTrailingZeros(NonZeros);
5699       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5700                                  Op.getOperand(Idx));
5701       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5702     }
5703     return SDValue();
5704   }
5705
5706   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5707   if (EVTBits == 8 && NumElems == 16) {
5708     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5709                                         Subtarget, *this);
5710     if (V.getNode()) return V;
5711   }
5712
5713   if (EVTBits == 16 && NumElems == 8) {
5714     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5715                                       Subtarget, *this);
5716     if (V.getNode()) return V;
5717   }
5718
5719   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5720   if (EVTBits == 32 && NumElems == 4) {
5721     SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
5722     if (V.getNode())
5723       return V;
5724   }
5725
5726   // If element VT is == 32 bits, turn it into a number of shuffles.
5727   SmallVector<SDValue, 8> V(NumElems);
5728   if (NumElems == 4 && NumZero > 0) {
5729     for (unsigned i = 0; i < 4; ++i) {
5730       bool isZero = !(NonZeros & (1 << i));
5731       if (isZero)
5732         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5733       else
5734         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5735     }
5736
5737     for (unsigned i = 0; i < 2; ++i) {
5738       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5739         default: break;
5740         case 0:
5741           V[i] = V[i*2];  // Must be a zero vector.
5742           break;
5743         case 1:
5744           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5745           break;
5746         case 2:
5747           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5748           break;
5749         case 3:
5750           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5751           break;
5752       }
5753     }
5754
5755     bool Reverse1 = (NonZeros & 0x3) == 2;
5756     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5757     int MaskVec[] = {
5758       Reverse1 ? 1 : 0,
5759       Reverse1 ? 0 : 1,
5760       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5761       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5762     };
5763     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5764   }
5765
5766   if (Values.size() > 1 && VT.is128BitVector()) {
5767     // Check for a build vector of consecutive loads.
5768     for (unsigned i = 0; i < NumElems; ++i)
5769       V[i] = Op.getOperand(i);
5770
5771     // Check for elements which are consecutive loads.
5772     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
5773     if (LD.getNode())
5774       return LD;
5775
5776     // Check for a build vector from mostly shuffle plus few inserting.
5777     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5778     if (Sh.getNode())
5779       return Sh;
5780
5781     // For SSE 4.1, use insertps to put the high elements into the low element.
5782     if (Subtarget->hasSSE41()) {
5783       SDValue Result;
5784       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5785         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5786       else
5787         Result = DAG.getUNDEF(VT);
5788
5789       for (unsigned i = 1; i < NumElems; ++i) {
5790         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5791         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5792                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5793       }
5794       return Result;
5795     }
5796
5797     // Otherwise, expand into a number of unpckl*, start by extending each of
5798     // our (non-undef) elements to the full vector width with the element in the
5799     // bottom slot of the vector (which generates no code for SSE).
5800     for (unsigned i = 0; i < NumElems; ++i) {
5801       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5802         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5803       else
5804         V[i] = DAG.getUNDEF(VT);
5805     }
5806
5807     // Next, we iteratively mix elements, e.g. for v4f32:
5808     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5809     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5810     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5811     unsigned EltStride = NumElems >> 1;
5812     while (EltStride != 0) {
5813       for (unsigned i = 0; i < EltStride; ++i) {
5814         // If V[i+EltStride] is undef and this is the first round of mixing,
5815         // then it is safe to just drop this shuffle: V[i] is already in the
5816         // right place, the one element (since it's the first round) being
5817         // inserted as undef can be dropped.  This isn't safe for successive
5818         // rounds because they will permute elements within both vectors.
5819         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5820             EltStride == NumElems/2)
5821           continue;
5822
5823         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5824       }
5825       EltStride >>= 1;
5826     }
5827     return V[0];
5828   }
5829   return SDValue();
5830 }
5831
5832 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5833 // to create 256-bit vectors from two other 128-bit ones.
5834 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5835   SDLoc dl(Op);
5836   MVT ResVT = Op.getSimpleValueType();
5837
5838   assert((ResVT.is256BitVector() ||
5839           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5840
5841   SDValue V1 = Op.getOperand(0);
5842   SDValue V2 = Op.getOperand(1);
5843   unsigned NumElems = ResVT.getVectorNumElements();
5844   if(ResVT.is256BitVector())
5845     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5846
5847   if (Op.getNumOperands() == 4) {
5848     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5849                                 ResVT.getVectorNumElements()/2);
5850     SDValue V3 = Op.getOperand(2);
5851     SDValue V4 = Op.getOperand(3);
5852     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5853       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5854   }
5855   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5856 }
5857
5858 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
5859                                        const X86Subtarget *Subtarget,
5860                                        SelectionDAG & DAG) {
5861   SDLoc dl(Op);
5862   MVT ResVT = Op.getSimpleValueType();
5863   unsigned NumOfOperands = Op.getNumOperands();
5864
5865   assert(isPowerOf2_32(NumOfOperands) &&
5866          "Unexpected number of operands in CONCAT_VECTORS");
5867
5868   if (NumOfOperands > 2) {
5869     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5870                                   ResVT.getVectorNumElements()/2);
5871     SmallVector<SDValue, 2> Ops;
5872     for (unsigned i = 0; i < NumOfOperands/2; i++)
5873       Ops.push_back(Op.getOperand(i));
5874     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5875     Ops.clear();
5876     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
5877       Ops.push_back(Op.getOperand(i));
5878     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5879     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
5880   }
5881
5882   SDValue V1 = Op.getOperand(0);
5883   SDValue V2 = Op.getOperand(1);
5884   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
5885   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
5886
5887   if (IsZeroV1 && IsZeroV2)
5888     return getZeroVector(ResVT, Subtarget, DAG, dl);
5889
5890   SDValue ZeroIdx = DAG.getIntPtrConstant(0);
5891   SDValue Undef = DAG.getUNDEF(ResVT);
5892   unsigned NumElems = ResVT.getVectorNumElements();
5893   SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
5894
5895   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
5896   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
5897   if (IsZeroV1)
5898     return V2;
5899
5900   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
5901   // Zero the upper bits of V1
5902   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
5903   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
5904   if (IsZeroV2)
5905     return V1;
5906   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
5907 }
5908
5909 static SDValue LowerCONCAT_VECTORS(SDValue Op, 
5910                                    const X86Subtarget *Subtarget,
5911                                    SelectionDAG &DAG) {
5912   MVT VT = Op.getSimpleValueType();
5913   if (VT.getVectorElementType() == MVT::i1)
5914     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
5915
5916   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5917          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5918           Op.getNumOperands() == 4)));
5919
5920   // AVX can use the vinsertf128 instruction to create 256-bit vectors
5921   // from two other 128-bit ones.
5922
5923   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5924   return LowerAVXCONCAT_VECTORS(Op, DAG);
5925 }
5926
5927
5928 //===----------------------------------------------------------------------===//
5929 // Vector shuffle lowering
5930 //
5931 // This is an experimental code path for lowering vector shuffles on x86. It is
5932 // designed to handle arbitrary vector shuffles and blends, gracefully
5933 // degrading performance as necessary. It works hard to recognize idiomatic
5934 // shuffles and lower them to optimal instruction patterns without leaving
5935 // a framework that allows reasonably efficient handling of all vector shuffle
5936 // patterns.
5937 //===----------------------------------------------------------------------===//
5938
5939 /// \brief Tiny helper function to identify a no-op mask.
5940 ///
5941 /// This is a somewhat boring predicate function. It checks whether the mask
5942 /// array input, which is assumed to be a single-input shuffle mask of the kind
5943 /// used by the X86 shuffle instructions (not a fully general
5944 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5945 /// in-place shuffle are 'no-op's.
5946 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5947   for (int i = 0, Size = Mask.size(); i < Size; ++i)
5948     if (Mask[i] != -1 && Mask[i] != i)
5949       return false;
5950   return true;
5951 }
5952
5953 /// \brief Helper function to classify a mask as a single-input mask.
5954 ///
5955 /// This isn't a generic single-input test because in the vector shuffle
5956 /// lowering we canonicalize single inputs to be the first input operand. This
5957 /// means we can more quickly test for a single input by only checking whether
5958 /// an input from the second operand exists. We also assume that the size of
5959 /// mask corresponds to the size of the input vectors which isn't true in the
5960 /// fully general case.
5961 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
5962   for (int M : Mask)
5963     if (M >= (int)Mask.size())
5964       return false;
5965   return true;
5966 }
5967
5968 /// \brief Test whether there are elements crossing 128-bit lanes in this
5969 /// shuffle mask.
5970 ///
5971 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
5972 /// and we routinely test for these.
5973 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
5974   int LaneSize = 128 / VT.getScalarSizeInBits();
5975   int Size = Mask.size();
5976   for (int i = 0; i < Size; ++i)
5977     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
5978       return true;
5979   return false;
5980 }
5981
5982 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
5983 ///
5984 /// This checks a shuffle mask to see if it is performing the same
5985 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
5986 /// that it is also not lane-crossing. It may however involve a blend from the
5987 /// same lane of a second vector.
5988 ///
5989 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
5990 /// non-trivial to compute in the face of undef lanes. The representation is
5991 /// *not* suitable for use with existing 128-bit shuffles as it will contain
5992 /// entries from both V1 and V2 inputs to the wider mask.
5993 static bool
5994 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
5995                                 SmallVectorImpl<int> &RepeatedMask) {
5996   int LaneSize = 128 / VT.getScalarSizeInBits();
5997   RepeatedMask.resize(LaneSize, -1);
5998   int Size = Mask.size();
5999   for (int i = 0; i < Size; ++i) {
6000     if (Mask[i] < 0)
6001       continue;
6002     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6003       // This entry crosses lanes, so there is no way to model this shuffle.
6004       return false;
6005
6006     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6007     if (RepeatedMask[i % LaneSize] == -1)
6008       // This is the first non-undef entry in this slot of a 128-bit lane.
6009       RepeatedMask[i % LaneSize] =
6010           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6011     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6012       // Found a mismatch with the repeated mask.
6013       return false;
6014   }
6015   return true;
6016 }
6017
6018 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6019 /// arguments.
6020 ///
6021 /// This is a fast way to test a shuffle mask against a fixed pattern:
6022 ///
6023 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6024 ///
6025 /// It returns true if the mask is exactly as wide as the argument list, and
6026 /// each element of the mask is either -1 (signifying undef) or the value given
6027 /// in the argument.
6028 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6029                                 ArrayRef<int> ExpectedMask) {
6030   if (Mask.size() != ExpectedMask.size())
6031     return false;
6032
6033   int Size = Mask.size();
6034
6035   // If the values are build vectors, we can look through them to find
6036   // equivalent inputs that make the shuffles equivalent.
6037   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6038   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6039
6040   for (int i = 0; i < Size; ++i)
6041     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6042       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6043       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6044       if (!MaskBV || !ExpectedBV ||
6045           MaskBV->getOperand(Mask[i] % Size) !=
6046               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6047         return false;
6048     }
6049
6050   return true;
6051 }
6052
6053 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6054 ///
6055 /// This helper function produces an 8-bit shuffle immediate corresponding to
6056 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6057 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6058 /// example.
6059 ///
6060 /// NB: We rely heavily on "undef" masks preserving the input lane.
6061 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6062                                           SelectionDAG &DAG) {
6063   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6064   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6065   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6066   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6067   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6068
6069   unsigned Imm = 0;
6070   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6071   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6072   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6073   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6074   return DAG.getConstant(Imm, MVT::i8);
6075 }
6076
6077 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6078 ///
6079 /// This is used as a fallback approach when first class blend instructions are
6080 /// unavailable. Currently it is only suitable for integer vectors, but could
6081 /// be generalized for floating point vectors if desirable.
6082 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6083                                             SDValue V2, ArrayRef<int> Mask,
6084                                             SelectionDAG &DAG) {
6085   assert(VT.isInteger() && "Only supports integer vector types!");
6086   MVT EltVT = VT.getScalarType();
6087   int NumEltBits = EltVT.getSizeInBits();
6088   SDValue Zero = DAG.getConstant(0, EltVT);
6089   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6090   SmallVector<SDValue, 16> MaskOps;
6091   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6092     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6093       return SDValue(); // Shuffled input!
6094     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6095   }
6096
6097   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6098   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6099   // We have to cast V2 around.
6100   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6101   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6102                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6103                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6104                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6105   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6106 }
6107
6108 /// \brief Try to emit a blend instruction for a shuffle.
6109 ///
6110 /// This doesn't do any checks for the availability of instructions for blending
6111 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6112 /// be matched in the backend with the type given. What it does check for is
6113 /// that the shuffle mask is in fact a blend.
6114 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6115                                          SDValue V2, ArrayRef<int> Mask,
6116                                          const X86Subtarget *Subtarget,
6117                                          SelectionDAG &DAG) {
6118   unsigned BlendMask = 0;
6119   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6120     if (Mask[i] >= Size) {
6121       if (Mask[i] != i + Size)
6122         return SDValue(); // Shuffled V2 input!
6123       BlendMask |= 1u << i;
6124       continue;
6125     }
6126     if (Mask[i] >= 0 && Mask[i] != i)
6127       return SDValue(); // Shuffled V1 input!
6128   }
6129   switch (VT.SimpleTy) {
6130   case MVT::v2f64:
6131   case MVT::v4f32:
6132   case MVT::v4f64:
6133   case MVT::v8f32:
6134     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6135                        DAG.getConstant(BlendMask, MVT::i8));
6136
6137   case MVT::v4i64:
6138   case MVT::v8i32:
6139     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6140     // FALLTHROUGH
6141   case MVT::v2i64:
6142   case MVT::v4i32:
6143     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6144     // that instruction.
6145     if (Subtarget->hasAVX2()) {
6146       // Scale the blend by the number of 32-bit dwords per element.
6147       int Scale =  VT.getScalarSizeInBits() / 32;
6148       BlendMask = 0;
6149       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6150         if (Mask[i] >= Size)
6151           for (int j = 0; j < Scale; ++j)
6152             BlendMask |= 1u << (i * Scale + j);
6153
6154       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6155       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6156       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6157       return DAG.getNode(ISD::BITCAST, DL, VT,
6158                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6159                                      DAG.getConstant(BlendMask, MVT::i8)));
6160     }
6161     // FALLTHROUGH
6162   case MVT::v8i16: {
6163     // For integer shuffles we need to expand the mask and cast the inputs to
6164     // v8i16s prior to blending.
6165     int Scale = 8 / VT.getVectorNumElements();
6166     BlendMask = 0;
6167     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6168       if (Mask[i] >= Size)
6169         for (int j = 0; j < Scale; ++j)
6170           BlendMask |= 1u << (i * Scale + j);
6171
6172     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6173     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6174     return DAG.getNode(ISD::BITCAST, DL, VT,
6175                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6176                                    DAG.getConstant(BlendMask, MVT::i8)));
6177   }
6178
6179   case MVT::v16i16: {
6180     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6181     SmallVector<int, 8> RepeatedMask;
6182     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6183       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6184       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6185       BlendMask = 0;
6186       for (int i = 0; i < 8; ++i)
6187         if (RepeatedMask[i] >= 16)
6188           BlendMask |= 1u << i;
6189       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6190                          DAG.getConstant(BlendMask, MVT::i8));
6191     }
6192   }
6193     // FALLTHROUGH
6194   case MVT::v16i8:
6195   case MVT::v32i8: {
6196     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6197            "256-bit byte-blends require AVX2 support!");
6198
6199     // Scale the blend by the number of bytes per element.
6200     int Scale = VT.getScalarSizeInBits() / 8;
6201
6202     // This form of blend is always done on bytes. Compute the byte vector
6203     // type.
6204     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6205
6206     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6207     // mix of LLVM's code generator and the x86 backend. We tell the code
6208     // generator that boolean values in the elements of an x86 vector register
6209     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6210     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6211     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6212     // of the element (the remaining are ignored) and 0 in that high bit would
6213     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6214     // the LLVM model for boolean values in vector elements gets the relevant
6215     // bit set, it is set backwards and over constrained relative to x86's
6216     // actual model.
6217     SmallVector<SDValue, 32> VSELECTMask;
6218     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6219       for (int j = 0; j < Scale; ++j)
6220         VSELECTMask.push_back(
6221             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6222                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6223
6224     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6225     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6226     return DAG.getNode(
6227         ISD::BITCAST, DL, VT,
6228         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6229                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6230                     V1, V2));
6231   }
6232
6233   default:
6234     llvm_unreachable("Not a supported integer vector type!");
6235   }
6236 }
6237
6238 /// \brief Try to lower as a blend of elements from two inputs followed by
6239 /// a single-input permutation.
6240 ///
6241 /// This matches the pattern where we can blend elements from two inputs and
6242 /// then reduce the shuffle to a single-input permutation.
6243 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6244                                                    SDValue V2,
6245                                                    ArrayRef<int> Mask,
6246                                                    SelectionDAG &DAG) {
6247   // We build up the blend mask while checking whether a blend is a viable way
6248   // to reduce the shuffle.
6249   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6250   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6251
6252   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6253     if (Mask[i] < 0)
6254       continue;
6255
6256     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6257
6258     if (BlendMask[Mask[i] % Size] == -1)
6259       BlendMask[Mask[i] % Size] = Mask[i];
6260     else if (BlendMask[Mask[i] % Size] != Mask[i])
6261       return SDValue(); // Can't blend in the needed input!
6262
6263     PermuteMask[i] = Mask[i] % Size;
6264   }
6265
6266   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6267   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6268 }
6269
6270 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6271 /// blends and permutes.
6272 ///
6273 /// This matches the extremely common pattern for handling combined
6274 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6275 /// operations. It will try to pick the best arrangement of shuffles and
6276 /// blends.
6277 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6278                                                           SDValue V1,
6279                                                           SDValue V2,
6280                                                           ArrayRef<int> Mask,
6281                                                           SelectionDAG &DAG) {
6282   // Shuffle the input elements into the desired positions in V1 and V2 and
6283   // blend them together.
6284   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6285   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6286   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6287   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6288     if (Mask[i] >= 0 && Mask[i] < Size) {
6289       V1Mask[i] = Mask[i];
6290       BlendMask[i] = i;
6291     } else if (Mask[i] >= Size) {
6292       V2Mask[i] = Mask[i] - Size;
6293       BlendMask[i] = i + Size;
6294     }
6295
6296   // Try to lower with the simpler initial blend strategy unless one of the
6297   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6298   // shuffle may be able to fold with a load or other benefit. However, when
6299   // we'll have to do 2x as many shuffles in order to achieve this, blending
6300   // first is a better strategy.
6301   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6302     if (SDValue BlendPerm =
6303             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6304       return BlendPerm;
6305
6306   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6307   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6308   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6309 }
6310
6311 /// \brief Try to lower a vector shuffle as a byte rotation.
6312 ///
6313 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6314 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6315 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6316 /// try to generically lower a vector shuffle through such an pattern. It
6317 /// does not check for the profitability of lowering either as PALIGNR or
6318 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6319 /// This matches shuffle vectors that look like:
6320 ///
6321 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6322 ///
6323 /// Essentially it concatenates V1 and V2, shifts right by some number of
6324 /// elements, and takes the low elements as the result. Note that while this is
6325 /// specified as a *right shift* because x86 is little-endian, it is a *left
6326 /// rotate* of the vector lanes.
6327 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6328                                               SDValue V2,
6329                                               ArrayRef<int> Mask,
6330                                               const X86Subtarget *Subtarget,
6331                                               SelectionDAG &DAG) {
6332   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6333
6334   int NumElts = Mask.size();
6335   int NumLanes = VT.getSizeInBits() / 128;
6336   int NumLaneElts = NumElts / NumLanes;
6337
6338   // We need to detect various ways of spelling a rotation:
6339   //   [11, 12, 13, 14, 15,  0,  1,  2]
6340   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6341   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6342   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6343   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6344   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6345   int Rotation = 0;
6346   SDValue Lo, Hi;
6347   for (int l = 0; l < NumElts; l += NumLaneElts) {
6348     for (int i = 0; i < NumLaneElts; ++i) {
6349       if (Mask[l + i] == -1)
6350         continue;
6351       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6352
6353       // Get the mod-Size index and lane correct it.
6354       int LaneIdx = (Mask[l + i] % NumElts) - l;
6355       // Make sure it was in this lane.
6356       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6357         return SDValue();
6358
6359       // Determine where a rotated vector would have started.
6360       int StartIdx = i - LaneIdx;
6361       if (StartIdx == 0)
6362         // The identity rotation isn't interesting, stop.
6363         return SDValue();
6364
6365       // If we found the tail of a vector the rotation must be the missing
6366       // front. If we found the head of a vector, it must be how much of the
6367       // head.
6368       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6369
6370       if (Rotation == 0)
6371         Rotation = CandidateRotation;
6372       else if (Rotation != CandidateRotation)
6373         // The rotations don't match, so we can't match this mask.
6374         return SDValue();
6375
6376       // Compute which value this mask is pointing at.
6377       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6378
6379       // Compute which of the two target values this index should be assigned
6380       // to. This reflects whether the high elements are remaining or the low
6381       // elements are remaining.
6382       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6383
6384       // Either set up this value if we've not encountered it before, or check
6385       // that it remains consistent.
6386       if (!TargetV)
6387         TargetV = MaskV;
6388       else if (TargetV != MaskV)
6389         // This may be a rotation, but it pulls from the inputs in some
6390         // unsupported interleaving.
6391         return SDValue();
6392     }
6393   }
6394
6395   // Check that we successfully analyzed the mask, and normalize the results.
6396   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6397   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6398   if (!Lo)
6399     Lo = Hi;
6400   else if (!Hi)
6401     Hi = Lo;
6402
6403   // The actual rotate instruction rotates bytes, so we need to scale the
6404   // rotation based on how many bytes are in the vector lane.
6405   int Scale = 16 / NumLaneElts;
6406
6407   // SSSE3 targets can use the palignr instruction.
6408   if (Subtarget->hasSSSE3()) {
6409     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6410     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6411     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6412     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6413
6414     return DAG.getNode(ISD::BITCAST, DL, VT,
6415                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6416                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
6417   }
6418
6419   assert(VT.getSizeInBits() == 128 &&
6420          "Rotate-based lowering only supports 128-bit lowering!");
6421   assert(Mask.size() <= 16 &&
6422          "Can shuffle at most 16 bytes in a 128-bit vector!");
6423
6424   // Default SSE2 implementation
6425   int LoByteShift = 16 - Rotation * Scale;
6426   int HiByteShift = Rotation * Scale;
6427
6428   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6429   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6430   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6431
6432   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6433                                 DAG.getConstant(LoByteShift, MVT::i8));
6434   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6435                                 DAG.getConstant(HiByteShift, MVT::i8));
6436   return DAG.getNode(ISD::BITCAST, DL, VT,
6437                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6438 }
6439
6440 /// \brief Compute whether each element of a shuffle is zeroable.
6441 ///
6442 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6443 /// Either it is an undef element in the shuffle mask, the element of the input
6444 /// referenced is undef, or the element of the input referenced is known to be
6445 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6446 /// as many lanes with this technique as possible to simplify the remaining
6447 /// shuffle.
6448 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6449                                                      SDValue V1, SDValue V2) {
6450   SmallBitVector Zeroable(Mask.size(), false);
6451
6452   while (V1.getOpcode() == ISD::BITCAST)
6453     V1 = V1->getOperand(0);
6454   while (V2.getOpcode() == ISD::BITCAST)
6455     V2 = V2->getOperand(0);
6456
6457   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6458   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6459
6460   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6461     int M = Mask[i];
6462     // Handle the easy cases.
6463     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6464       Zeroable[i] = true;
6465       continue;
6466     }
6467
6468     // If this is an index into a build_vector node (which has the same number
6469     // of elements), dig out the input value and use it.
6470     SDValue V = M < Size ? V1 : V2;
6471     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6472       continue;
6473
6474     SDValue Input = V.getOperand(M % Size);
6475     // The UNDEF opcode check really should be dead code here, but not quite
6476     // worth asserting on (it isn't invalid, just unexpected).
6477     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6478       Zeroable[i] = true;
6479   }
6480
6481   return Zeroable;
6482 }
6483
6484 /// \brief Try to emit a bitmask instruction for a shuffle.
6485 ///
6486 /// This handles cases where we can model a blend exactly as a bitmask due to
6487 /// one of the inputs being zeroable.
6488 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6489                                            SDValue V2, ArrayRef<int> Mask,
6490                                            SelectionDAG &DAG) {
6491   MVT EltVT = VT.getScalarType();
6492   int NumEltBits = EltVT.getSizeInBits();
6493   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6494   SDValue Zero = DAG.getConstant(0, IntEltVT);
6495   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6496   if (EltVT.isFloatingPoint()) {
6497     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6498     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6499   }
6500   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6501   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6502   SDValue V;
6503   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6504     if (Zeroable[i])
6505       continue;
6506     if (Mask[i] % Size != i)
6507       return SDValue(); // Not a blend.
6508     if (!V)
6509       V = Mask[i] < Size ? V1 : V2;
6510     else if (V != (Mask[i] < Size ? V1 : V2))
6511       return SDValue(); // Can only let one input through the mask.
6512
6513     VMaskOps[i] = AllOnes;
6514   }
6515   if (!V)
6516     return SDValue(); // No non-zeroable elements!
6517
6518   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6519   V = DAG.getNode(VT.isFloatingPoint()
6520                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6521                   DL, VT, V, VMask);
6522   return V;
6523 }
6524
6525 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6526 ///
6527 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6528 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6529 /// matches elements from one of the input vectors shuffled to the left or
6530 /// right with zeroable elements 'shifted in'. It handles both the strictly
6531 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6532 /// quad word lane.
6533 ///
6534 /// PSHL : (little-endian) left bit shift.
6535 /// [ zz, 0, zz,  2 ]
6536 /// [ -1, 4, zz, -1 ]
6537 /// PSRL : (little-endian) right bit shift.
6538 /// [  1, zz,  3, zz]
6539 /// [ -1, -1,  7, zz]
6540 /// PSLLDQ : (little-endian) left byte shift
6541 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6542 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6543 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6544 /// PSRLDQ : (little-endian) right byte shift
6545 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6546 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6547 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6548 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6549                                          SDValue V2, ArrayRef<int> Mask,
6550                                          SelectionDAG &DAG) {
6551   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6552
6553   int Size = Mask.size();
6554   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6555
6556   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6557     for (int i = 0; i < Size; i += Scale)
6558       for (int j = 0; j < Shift; ++j)
6559         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6560           return false;
6561
6562     return true;
6563   };
6564
6565   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6566     for (int i = 0; i != Size; i += Scale) {
6567       unsigned Pos = Left ? i + Shift : i;
6568       unsigned Low = Left ? i : i + Shift;
6569       unsigned Len = Scale - Shift;
6570       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6571                                       Low + (V == V1 ? 0 : Size)))
6572         return SDValue();
6573     }
6574
6575     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6576     bool ByteShift = ShiftEltBits > 64;
6577     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6578                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6579     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6580
6581     // Normalize the scale for byte shifts to still produce an i64 element
6582     // type.
6583     Scale = ByteShift ? Scale / 2 : Scale;
6584
6585     // We need to round trip through the appropriate type for the shift.
6586     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6587     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6588     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6589            "Illegal integer vector type");
6590     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6591
6592     V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6593     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6594   };
6595
6596   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6597   // keep doubling the size of the integer elements up to that. We can
6598   // then shift the elements of the integer vector by whole multiples of
6599   // their width within the elements of the larger integer vector. Test each
6600   // multiple to see if we can find a match with the moved element indices
6601   // and that the shifted in elements are all zeroable.
6602   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6603     for (int Shift = 1; Shift != Scale; ++Shift)
6604       for (bool Left : {true, false})
6605         if (CheckZeros(Shift, Scale, Left))
6606           for (SDValue V : {V1, V2})
6607             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6608               return Match;
6609
6610   // no match
6611   return SDValue();
6612 }
6613
6614 /// \brief Lower a vector shuffle as a zero or any extension.
6615 ///
6616 /// Given a specific number of elements, element bit width, and extension
6617 /// stride, produce either a zero or any extension based on the available
6618 /// features of the subtarget.
6619 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6620     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6621     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6622   assert(Scale > 1 && "Need a scale to extend.");
6623   int NumElements = VT.getVectorNumElements();
6624   int EltBits = VT.getScalarSizeInBits();
6625   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6626          "Only 8, 16, and 32 bit elements can be extended.");
6627   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6628
6629   // Found a valid zext mask! Try various lowering strategies based on the
6630   // input type and available ISA extensions.
6631   if (Subtarget->hasSSE41()) {
6632     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6633                                  NumElements / Scale);
6634     return DAG.getNode(ISD::BITCAST, DL, VT,
6635                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6636   }
6637
6638   // For any extends we can cheat for larger element sizes and use shuffle
6639   // instructions that can fold with a load and/or copy.
6640   if (AnyExt && EltBits == 32) {
6641     int PSHUFDMask[4] = {0, -1, 1, -1};
6642     return DAG.getNode(
6643         ISD::BITCAST, DL, VT,
6644         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6645                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6646                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6647   }
6648   if (AnyExt && EltBits == 16 && Scale > 2) {
6649     int PSHUFDMask[4] = {0, -1, 0, -1};
6650     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6651                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6652                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6653     int PSHUFHWMask[4] = {1, -1, -1, -1};
6654     return DAG.getNode(
6655         ISD::BITCAST, DL, VT,
6656         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6657                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6658                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6659   }
6660
6661   // If this would require more than 2 unpack instructions to expand, use
6662   // pshufb when available. We can only use more than 2 unpack instructions
6663   // when zero extending i8 elements which also makes it easier to use pshufb.
6664   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6665     assert(NumElements == 16 && "Unexpected byte vector width!");
6666     SDValue PSHUFBMask[16];
6667     for (int i = 0; i < 16; ++i)
6668       PSHUFBMask[i] =
6669           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6670     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6671     return DAG.getNode(ISD::BITCAST, DL, VT,
6672                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6673                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6674                                                MVT::v16i8, PSHUFBMask)));
6675   }
6676
6677   // Otherwise emit a sequence of unpacks.
6678   do {
6679     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6680     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6681                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6682     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6683     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6684     Scale /= 2;
6685     EltBits *= 2;
6686     NumElements /= 2;
6687   } while (Scale > 1);
6688   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6689 }
6690
6691 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6692 ///
6693 /// This routine will try to do everything in its power to cleverly lower
6694 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6695 /// check for the profitability of this lowering,  it tries to aggressively
6696 /// match this pattern. It will use all of the micro-architectural details it
6697 /// can to emit an efficient lowering. It handles both blends with all-zero
6698 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6699 /// masking out later).
6700 ///
6701 /// The reason we have dedicated lowering for zext-style shuffles is that they
6702 /// are both incredibly common and often quite performance sensitive.
6703 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6704     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6705     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6706   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6707
6708   int Bits = VT.getSizeInBits();
6709   int NumElements = VT.getVectorNumElements();
6710   assert(VT.getScalarSizeInBits() <= 32 &&
6711          "Exceeds 32-bit integer zero extension limit");
6712   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6713
6714   // Define a helper function to check a particular ext-scale and lower to it if
6715   // valid.
6716   auto Lower = [&](int Scale) -> SDValue {
6717     SDValue InputV;
6718     bool AnyExt = true;
6719     for (int i = 0; i < NumElements; ++i) {
6720       if (Mask[i] == -1)
6721         continue; // Valid anywhere but doesn't tell us anything.
6722       if (i % Scale != 0) {
6723         // Each of the extended elements need to be zeroable.
6724         if (!Zeroable[i])
6725           return SDValue();
6726
6727         // We no longer are in the anyext case.
6728         AnyExt = false;
6729         continue;
6730       }
6731
6732       // Each of the base elements needs to be consecutive indices into the
6733       // same input vector.
6734       SDValue V = Mask[i] < NumElements ? V1 : V2;
6735       if (!InputV)
6736         InputV = V;
6737       else if (InputV != V)
6738         return SDValue(); // Flip-flopping inputs.
6739
6740       if (Mask[i] % NumElements != i / Scale)
6741         return SDValue(); // Non-consecutive strided elements.
6742     }
6743
6744     // If we fail to find an input, we have a zero-shuffle which should always
6745     // have already been handled.
6746     // FIXME: Maybe handle this here in case during blending we end up with one?
6747     if (!InputV)
6748       return SDValue();
6749
6750     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6751         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6752   };
6753
6754   // The widest scale possible for extending is to a 64-bit integer.
6755   assert(Bits % 64 == 0 &&
6756          "The number of bits in a vector must be divisible by 64 on x86!");
6757   int NumExtElements = Bits / 64;
6758
6759   // Each iteration, try extending the elements half as much, but into twice as
6760   // many elements.
6761   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6762     assert(NumElements % NumExtElements == 0 &&
6763            "The input vector size must be divisible by the extended size.");
6764     if (SDValue V = Lower(NumElements / NumExtElements))
6765       return V;
6766   }
6767
6768   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6769   if (Bits != 128)
6770     return SDValue();
6771
6772   // Returns one of the source operands if the shuffle can be reduced to a
6773   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6774   auto CanZExtLowHalf = [&]() {
6775     for (int i = NumElements / 2; i != NumElements; ++i)
6776       if (!Zeroable[i])
6777         return SDValue();
6778     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6779       return V1;
6780     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6781       return V2;
6782     return SDValue();
6783   };
6784
6785   if (SDValue V = CanZExtLowHalf()) {
6786     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6787     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6788     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6789   }
6790
6791   // No viable ext lowering found.
6792   return SDValue();
6793 }
6794
6795 /// \brief Try to get a scalar value for a specific element of a vector.
6796 ///
6797 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6798 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6799                                               SelectionDAG &DAG) {
6800   MVT VT = V.getSimpleValueType();
6801   MVT EltVT = VT.getVectorElementType();
6802   while (V.getOpcode() == ISD::BITCAST)
6803     V = V.getOperand(0);
6804   // If the bitcasts shift the element size, we can't extract an equivalent
6805   // element from it.
6806   MVT NewVT = V.getSimpleValueType();
6807   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6808     return SDValue();
6809
6810   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6811       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6812     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6813
6814   return SDValue();
6815 }
6816
6817 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6818 ///
6819 /// This is particularly important because the set of instructions varies
6820 /// significantly based on whether the operand is a load or not.
6821 static bool isShuffleFoldableLoad(SDValue V) {
6822   while (V.getOpcode() == ISD::BITCAST)
6823     V = V.getOperand(0);
6824
6825   return ISD::isNON_EXTLoad(V.getNode());
6826 }
6827
6828 /// \brief Try to lower insertion of a single element into a zero vector.
6829 ///
6830 /// This is a common pattern that we have especially efficient patterns to lower
6831 /// across all subtarget feature sets.
6832 static SDValue lowerVectorShuffleAsElementInsertion(
6833     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6834     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6835   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6836   MVT ExtVT = VT;
6837   MVT EltVT = VT.getVectorElementType();
6838
6839   int V2Index = std::find_if(Mask.begin(), Mask.end(),
6840                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
6841                 Mask.begin();
6842   bool IsV1Zeroable = true;
6843   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6844     if (i != V2Index && !Zeroable[i]) {
6845       IsV1Zeroable = false;
6846       break;
6847     }
6848
6849   // Check for a single input from a SCALAR_TO_VECTOR node.
6850   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6851   // all the smarts here sunk into that routine. However, the current
6852   // lowering of BUILD_VECTOR makes that nearly impossible until the old
6853   // vector shuffle lowering is dead.
6854   if (SDValue V2S = getScalarValueForVectorElement(
6855           V2, Mask[V2Index] - Mask.size(), DAG)) {
6856     // We need to zext the scalar if it is smaller than an i32.
6857     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6858     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6859       // Using zext to expand a narrow element won't work for non-zero
6860       // insertions.
6861       if (!IsV1Zeroable)
6862         return SDValue();
6863
6864       // Zero-extend directly to i32.
6865       ExtVT = MVT::v4i32;
6866       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6867     }
6868     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6869   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6870              EltVT == MVT::i16) {
6871     // Either not inserting from the low element of the input or the input
6872     // element size is too small to use VZEXT_MOVL to clear the high bits.
6873     return SDValue();
6874   }
6875
6876   if (!IsV1Zeroable) {
6877     // If V1 can't be treated as a zero vector we have fewer options to lower
6878     // this. We can't support integer vectors or non-zero targets cheaply, and
6879     // the V1 elements can't be permuted in any way.
6880     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6881     if (!VT.isFloatingPoint() || V2Index != 0)
6882       return SDValue();
6883     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6884     V1Mask[V2Index] = -1;
6885     if (!isNoopShuffleMask(V1Mask))
6886       return SDValue();
6887     // This is essentially a special case blend operation, but if we have
6888     // general purpose blend operations, they are always faster. Bail and let
6889     // the rest of the lowering handle these as blends.
6890     if (Subtarget->hasSSE41())
6891       return SDValue();
6892
6893     // Otherwise, use MOVSD or MOVSS.
6894     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6895            "Only two types of floating point element types to handle!");
6896     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6897                        ExtVT, V1, V2);
6898   }
6899
6900   // This lowering only works for the low element with floating point vectors.
6901   if (VT.isFloatingPoint() && V2Index != 0)
6902     return SDValue();
6903
6904   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6905   if (ExtVT != VT)
6906     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6907
6908   if (V2Index != 0) {
6909     // If we have 4 or fewer lanes we can cheaply shuffle the element into
6910     // the desired position. Otherwise it is more efficient to do a vector
6911     // shift left. We know that we can do a vector shift left because all
6912     // the inputs are zero.
6913     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6914       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6915       V2Shuffle[V2Index] = 0;
6916       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6917     } else {
6918       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6919       V2 = DAG.getNode(
6920           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6921           DAG.getConstant(
6922               V2Index * EltVT.getSizeInBits()/8,
6923               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6924       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6925     }
6926   }
6927   return V2;
6928 }
6929
6930 /// \brief Try to lower broadcast of a single element.
6931 ///
6932 /// For convenience, this code also bundles all of the subtarget feature set
6933 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6934 /// a convenient way to factor it out.
6935 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
6936                                              ArrayRef<int> Mask,
6937                                              const X86Subtarget *Subtarget,
6938                                              SelectionDAG &DAG) {
6939   if (!Subtarget->hasAVX())
6940     return SDValue();
6941   if (VT.isInteger() && !Subtarget->hasAVX2())
6942     return SDValue();
6943
6944   // Check that the mask is a broadcast.
6945   int BroadcastIdx = -1;
6946   for (int M : Mask)
6947     if (M >= 0 && BroadcastIdx == -1)
6948       BroadcastIdx = M;
6949     else if (M >= 0 && M != BroadcastIdx)
6950       return SDValue();
6951
6952   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6953                                             "a sorted mask where the broadcast "
6954                                             "comes from V1.");
6955
6956   // Go up the chain of (vector) values to try and find a scalar load that
6957   // we can combine with the broadcast.
6958   for (;;) {
6959     switch (V.getOpcode()) {
6960     case ISD::CONCAT_VECTORS: {
6961       int OperandSize = Mask.size() / V.getNumOperands();
6962       V = V.getOperand(BroadcastIdx / OperandSize);
6963       BroadcastIdx %= OperandSize;
6964       continue;
6965     }
6966
6967     case ISD::INSERT_SUBVECTOR: {
6968       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
6969       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
6970       if (!ConstantIdx)
6971         break;
6972
6973       int BeginIdx = (int)ConstantIdx->getZExtValue();
6974       int EndIdx =
6975           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
6976       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
6977         BroadcastIdx -= BeginIdx;
6978         V = VInner;
6979       } else {
6980         V = VOuter;
6981       }
6982       continue;
6983     }
6984     }
6985     break;
6986   }
6987
6988   // Check if this is a broadcast of a scalar. We special case lowering
6989   // for scalars so that we can more effectively fold with loads.
6990   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6991       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
6992     V = V.getOperand(BroadcastIdx);
6993
6994     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
6995     // AVX2.
6996     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
6997       return SDValue();
6998   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
6999     // We can't broadcast from a vector register w/o AVX2, and we can only
7000     // broadcast from the zero-element of a vector register.
7001     return SDValue();
7002   }
7003
7004   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7005 }
7006
7007 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7008 // INSERTPS when the V1 elements are already in the correct locations
7009 // because otherwise we can just always use two SHUFPS instructions which
7010 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7011 // perform INSERTPS if a single V1 element is out of place and all V2
7012 // elements are zeroable.
7013 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7014                                             ArrayRef<int> Mask,
7015                                             SelectionDAG &DAG) {
7016   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7017   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7018   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7019   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7020
7021   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7022
7023   unsigned ZMask = 0;
7024   int V1DstIndex = -1;
7025   int V2DstIndex = -1;
7026   bool V1UsedInPlace = false;
7027
7028   for (int i = 0; i < 4; ++i) {
7029     // Synthesize a zero mask from the zeroable elements (includes undefs).
7030     if (Zeroable[i]) {
7031       ZMask |= 1 << i;
7032       continue;
7033     }
7034
7035     // Flag if we use any V1 inputs in place.
7036     if (i == Mask[i]) {
7037       V1UsedInPlace = true;
7038       continue;
7039     }
7040
7041     // We can only insert a single non-zeroable element.
7042     if (V1DstIndex != -1 || V2DstIndex != -1)
7043       return SDValue();
7044
7045     if (Mask[i] < 4) {
7046       // V1 input out of place for insertion.
7047       V1DstIndex = i;
7048     } else {
7049       // V2 input for insertion.
7050       V2DstIndex = i;
7051     }
7052   }
7053
7054   // Don't bother if we have no (non-zeroable) element for insertion.
7055   if (V1DstIndex == -1 && V2DstIndex == -1)
7056     return SDValue();
7057
7058   // Determine element insertion src/dst indices. The src index is from the
7059   // start of the inserted vector, not the start of the concatenated vector.
7060   unsigned V2SrcIndex = 0;
7061   if (V1DstIndex != -1) {
7062     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7063     // and don't use the original V2 at all.
7064     V2SrcIndex = Mask[V1DstIndex];
7065     V2DstIndex = V1DstIndex;
7066     V2 = V1;
7067   } else {
7068     V2SrcIndex = Mask[V2DstIndex] - 4;
7069   }
7070
7071   // If no V1 inputs are used in place, then the result is created only from
7072   // the zero mask and the V2 insertion - so remove V1 dependency.
7073   if (!V1UsedInPlace)
7074     V1 = DAG.getUNDEF(MVT::v4f32);
7075
7076   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7077   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7078
7079   // Insert the V2 element into the desired position.
7080   SDLoc DL(Op);
7081   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7082                      DAG.getConstant(InsertPSMask, MVT::i8));
7083 }
7084
7085 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7086 /// UNPCK instruction.
7087 ///
7088 /// This specifically targets cases where we end up with alternating between
7089 /// the two inputs, and so can permute them into something that feeds a single
7090 /// UNPCK instruction. Note that this routine only targets integer vectors
7091 /// because for floating point vectors we have a generalized SHUFPS lowering
7092 /// strategy that handles everything that doesn't *exactly* match an unpack,
7093 /// making this clever lowering unnecessary.
7094 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7095                                           SDValue V2, ArrayRef<int> Mask,
7096                                           SelectionDAG &DAG) {
7097   assert(!VT.isFloatingPoint() &&
7098          "This routine only supports integer vectors.");
7099   assert(!isSingleInputShuffleMask(Mask) &&
7100          "This routine should only be used when blending two inputs.");
7101   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7102
7103   int Size = Mask.size();
7104
7105   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7106     return M >= 0 && M % Size < Size / 2;
7107   });
7108   int NumHiInputs = std::count_if(
7109       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7110
7111   bool UnpackLo = NumLoInputs >= NumHiInputs;
7112
7113   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7114     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7115     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7116
7117     for (int i = 0; i < Size; ++i) {
7118       if (Mask[i] < 0)
7119         continue;
7120
7121       // Each element of the unpack contains Scale elements from this mask.
7122       int UnpackIdx = i / Scale;
7123
7124       // We only handle the case where V1 feeds the first slots of the unpack.
7125       // We rely on canonicalization to ensure this is the case.
7126       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7127         return SDValue();
7128
7129       // Setup the mask for this input. The indexing is tricky as we have to
7130       // handle the unpack stride.
7131       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7132       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7133           Mask[i] % Size;
7134     }
7135
7136     // If we will have to shuffle both inputs to use the unpack, check whether
7137     // we can just unpack first and shuffle the result. If so, skip this unpack.
7138     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7139         !isNoopShuffleMask(V2Mask))
7140       return SDValue();
7141
7142     // Shuffle the inputs into place.
7143     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7144     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7145
7146     // Cast the inputs to the type we will use to unpack them.
7147     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7148     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7149
7150     // Unpack the inputs and cast the result back to the desired type.
7151     return DAG.getNode(ISD::BITCAST, DL, VT,
7152                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7153                                    DL, UnpackVT, V1, V2));
7154   };
7155
7156   // We try each unpack from the largest to the smallest to try and find one
7157   // that fits this mask.
7158   int OrigNumElements = VT.getVectorNumElements();
7159   int OrigScalarSize = VT.getScalarSizeInBits();
7160   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7161     int Scale = ScalarSize / OrigScalarSize;
7162     int NumElements = OrigNumElements / Scale;
7163     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7164     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7165       return Unpack;
7166   }
7167
7168   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7169   // initial unpack.
7170   if (NumLoInputs == 0 || NumHiInputs == 0) {
7171     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7172            "We have to have *some* inputs!");
7173     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7174
7175     // FIXME: We could consider the total complexity of the permute of each
7176     // possible unpacking. Or at the least we should consider how many
7177     // half-crossings are created.
7178     // FIXME: We could consider commuting the unpacks.
7179
7180     SmallVector<int, 32> PermMask;
7181     PermMask.assign(Size, -1);
7182     for (int i = 0; i < Size; ++i) {
7183       if (Mask[i] < 0)
7184         continue;
7185
7186       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7187
7188       PermMask[i] =
7189           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7190     }
7191     return DAG.getVectorShuffle(
7192         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7193                             DL, VT, V1, V2),
7194         DAG.getUNDEF(VT), PermMask);
7195   }
7196
7197   return SDValue();
7198 }
7199
7200 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7201 ///
7202 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7203 /// support for floating point shuffles but not integer shuffles. These
7204 /// instructions will incur a domain crossing penalty on some chips though so
7205 /// it is better to avoid lowering through this for integer vectors where
7206 /// possible.
7207 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7208                                        const X86Subtarget *Subtarget,
7209                                        SelectionDAG &DAG) {
7210   SDLoc DL(Op);
7211   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7212   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7213   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7214   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7215   ArrayRef<int> Mask = SVOp->getMask();
7216   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7217
7218   if (isSingleInputShuffleMask(Mask)) {
7219     // Use low duplicate instructions for masks that match their pattern.
7220     if (Subtarget->hasSSE3())
7221       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7222         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7223
7224     // Straight shuffle of a single input vector. Simulate this by using the
7225     // single input as both of the "inputs" to this instruction..
7226     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7227
7228     if (Subtarget->hasAVX()) {
7229       // If we have AVX, we can use VPERMILPS which will allow folding a load
7230       // into the shuffle.
7231       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7232                          DAG.getConstant(SHUFPDMask, MVT::i8));
7233     }
7234
7235     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7236                        DAG.getConstant(SHUFPDMask, MVT::i8));
7237   }
7238   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7239   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7240
7241   // If we have a single input, insert that into V1 if we can do so cheaply.
7242   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7243     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7244             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7245       return Insertion;
7246     // Try inverting the insertion since for v2 masks it is easy to do and we
7247     // can't reliably sort the mask one way or the other.
7248     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7249                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7250     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7251             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7252       return Insertion;
7253   }
7254
7255   // Try to use one of the special instruction patterns to handle two common
7256   // blend patterns if a zero-blend above didn't work.
7257   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7258       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7259     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7260       // We can either use a special instruction to load over the low double or
7261       // to move just the low double.
7262       return DAG.getNode(
7263           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7264           DL, MVT::v2f64, V2,
7265           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7266
7267   if (Subtarget->hasSSE41())
7268     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7269                                                   Subtarget, DAG))
7270       return Blend;
7271
7272   // Use dedicated unpack instructions for masks that match their pattern.
7273   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7274     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7275   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7276     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7277
7278   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7279   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7280                      DAG.getConstant(SHUFPDMask, MVT::i8));
7281 }
7282
7283 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7284 ///
7285 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7286 /// the integer unit to minimize domain crossing penalties. However, for blends
7287 /// it falls back to the floating point shuffle operation with appropriate bit
7288 /// casting.
7289 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7290                                        const X86Subtarget *Subtarget,
7291                                        SelectionDAG &DAG) {
7292   SDLoc DL(Op);
7293   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7294   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7295   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7296   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7297   ArrayRef<int> Mask = SVOp->getMask();
7298   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7299
7300   if (isSingleInputShuffleMask(Mask)) {
7301     // Check for being able to broadcast a single element.
7302     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7303                                                           Mask, Subtarget, DAG))
7304       return Broadcast;
7305
7306     // Straight shuffle of a single input vector. For everything from SSE2
7307     // onward this has a single fast instruction with no scary immediates.
7308     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7309     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7310     int WidenedMask[4] = {
7311         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7312         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7313     return DAG.getNode(
7314         ISD::BITCAST, DL, MVT::v2i64,
7315         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7316                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7317   }
7318   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7319   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7320   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7321   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7322
7323   // If we have a blend of two PACKUS operations an the blend aligns with the
7324   // low and half halves, we can just merge the PACKUS operations. This is
7325   // particularly important as it lets us merge shuffles that this routine itself
7326   // creates.
7327   auto GetPackNode = [](SDValue V) {
7328     while (V.getOpcode() == ISD::BITCAST)
7329       V = V.getOperand(0);
7330
7331     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7332   };
7333   if (SDValue V1Pack = GetPackNode(V1))
7334     if (SDValue V2Pack = GetPackNode(V2))
7335       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7336                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7337                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7338                                                   : V1Pack.getOperand(1),
7339                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7340                                                   : V2Pack.getOperand(1)));
7341
7342   // Try to use shift instructions.
7343   if (SDValue Shift =
7344           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7345     return Shift;
7346
7347   // When loading a scalar and then shuffling it into a vector we can often do
7348   // the insertion cheaply.
7349   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7350           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7351     return Insertion;
7352   // Try inverting the insertion since for v2 masks it is easy to do and we
7353   // can't reliably sort the mask one way or the other.
7354   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7355   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7356           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7357     return Insertion;
7358
7359   // We have different paths for blend lowering, but they all must use the
7360   // *exact* same predicate.
7361   bool IsBlendSupported = Subtarget->hasSSE41();
7362   if (IsBlendSupported)
7363     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7364                                                   Subtarget, DAG))
7365       return Blend;
7366
7367   // Use dedicated unpack instructions for masks that match their pattern.
7368   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7369     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7370   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7371     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7372
7373   // Try to use byte rotation instructions.
7374   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7375   if (Subtarget->hasSSSE3())
7376     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7377             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7378       return Rotate;
7379
7380   // If we have direct support for blends, we should lower by decomposing into
7381   // a permute. That will be faster than the domain cross.
7382   if (IsBlendSupported)
7383     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7384                                                       Mask, DAG);
7385
7386   // We implement this with SHUFPD which is pretty lame because it will likely
7387   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7388   // However, all the alternatives are still more cycles and newer chips don't
7389   // have this problem. It would be really nice if x86 had better shuffles here.
7390   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7391   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7392   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7393                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7394 }
7395
7396 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7397 ///
7398 /// This is used to disable more specialized lowerings when the shufps lowering
7399 /// will happen to be efficient.
7400 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7401   // This routine only handles 128-bit shufps.
7402   assert(Mask.size() == 4 && "Unsupported mask size!");
7403
7404   // To lower with a single SHUFPS we need to have the low half and high half
7405   // each requiring a single input.
7406   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7407     return false;
7408   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7409     return false;
7410
7411   return true;
7412 }
7413
7414 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7415 ///
7416 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7417 /// It makes no assumptions about whether this is the *best* lowering, it simply
7418 /// uses it.
7419 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7420                                             ArrayRef<int> Mask, SDValue V1,
7421                                             SDValue V2, SelectionDAG &DAG) {
7422   SDValue LowV = V1, HighV = V2;
7423   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7424
7425   int NumV2Elements =
7426       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7427
7428   if (NumV2Elements == 1) {
7429     int V2Index =
7430         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7431         Mask.begin();
7432
7433     // Compute the index adjacent to V2Index and in the same half by toggling
7434     // the low bit.
7435     int V2AdjIndex = V2Index ^ 1;
7436
7437     if (Mask[V2AdjIndex] == -1) {
7438       // Handles all the cases where we have a single V2 element and an undef.
7439       // This will only ever happen in the high lanes because we commute the
7440       // vector otherwise.
7441       if (V2Index < 2)
7442         std::swap(LowV, HighV);
7443       NewMask[V2Index] -= 4;
7444     } else {
7445       // Handle the case where the V2 element ends up adjacent to a V1 element.
7446       // To make this work, blend them together as the first step.
7447       int V1Index = V2AdjIndex;
7448       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7449       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7450                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7451
7452       // Now proceed to reconstruct the final blend as we have the necessary
7453       // high or low half formed.
7454       if (V2Index < 2) {
7455         LowV = V2;
7456         HighV = V1;
7457       } else {
7458         HighV = V2;
7459       }
7460       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7461       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7462     }
7463   } else if (NumV2Elements == 2) {
7464     if (Mask[0] < 4 && Mask[1] < 4) {
7465       // Handle the easy case where we have V1 in the low lanes and V2 in the
7466       // high lanes.
7467       NewMask[2] -= 4;
7468       NewMask[3] -= 4;
7469     } else if (Mask[2] < 4 && Mask[3] < 4) {
7470       // We also handle the reversed case because this utility may get called
7471       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7472       // arrange things in the right direction.
7473       NewMask[0] -= 4;
7474       NewMask[1] -= 4;
7475       HighV = V1;
7476       LowV = V2;
7477     } else {
7478       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7479       // trying to place elements directly, just blend them and set up the final
7480       // shuffle to place them.
7481
7482       // The first two blend mask elements are for V1, the second two are for
7483       // V2.
7484       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7485                           Mask[2] < 4 ? Mask[2] : Mask[3],
7486                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7487                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7488       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7489                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7490
7491       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7492       // a blend.
7493       LowV = HighV = V1;
7494       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7495       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7496       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7497       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7498     }
7499   }
7500   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7501                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7502 }
7503
7504 /// \brief Lower 4-lane 32-bit floating point shuffles.
7505 ///
7506 /// Uses instructions exclusively from the floating point unit to minimize
7507 /// domain crossing penalties, as these are sufficient to implement all v4f32
7508 /// shuffles.
7509 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7510                                        const X86Subtarget *Subtarget,
7511                                        SelectionDAG &DAG) {
7512   SDLoc DL(Op);
7513   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7514   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7515   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7516   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7517   ArrayRef<int> Mask = SVOp->getMask();
7518   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7519
7520   int NumV2Elements =
7521       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7522
7523   if (NumV2Elements == 0) {
7524     // Check for being able to broadcast a single element.
7525     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7526                                                           Mask, Subtarget, DAG))
7527       return Broadcast;
7528
7529     // Use even/odd duplicate instructions for masks that match their pattern.
7530     if (Subtarget->hasSSE3()) {
7531       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7532         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7533       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7534         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7535     }
7536
7537     if (Subtarget->hasAVX()) {
7538       // If we have AVX, we can use VPERMILPS which will allow folding a load
7539       // into the shuffle.
7540       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7541                          getV4X86ShuffleImm8ForMask(Mask, DAG));
7542     }
7543
7544     // Otherwise, use a straight shuffle of a single input vector. We pass the
7545     // input vector to both operands to simulate this with a SHUFPS.
7546     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7547                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7548   }
7549
7550   // There are special ways we can lower some single-element blends. However, we
7551   // have custom ways we can lower more complex single-element blends below that
7552   // we defer to if both this and BLENDPS fail to match, so restrict this to
7553   // when the V2 input is targeting element 0 of the mask -- that is the fast
7554   // case here.
7555   if (NumV2Elements == 1 && Mask[0] >= 4)
7556     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7557                                                          Mask, Subtarget, DAG))
7558       return V;
7559
7560   if (Subtarget->hasSSE41()) {
7561     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7562                                                   Subtarget, DAG))
7563       return Blend;
7564
7565     // Use INSERTPS if we can complete the shuffle efficiently.
7566     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7567       return V;
7568
7569     if (!isSingleSHUFPSMask(Mask))
7570       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7571               DL, MVT::v4f32, V1, V2, Mask, DAG))
7572         return BlendPerm;
7573   }
7574
7575   // Use dedicated unpack instructions for masks that match their pattern.
7576   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7577     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7578   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7579     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7580   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7581     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7582   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7583     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7584
7585   // Otherwise fall back to a SHUFPS lowering strategy.
7586   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7587 }
7588
7589 /// \brief Lower 4-lane i32 vector shuffles.
7590 ///
7591 /// We try to handle these with integer-domain shuffles where we can, but for
7592 /// blends we use the floating point domain blend instructions.
7593 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7594                                        const X86Subtarget *Subtarget,
7595                                        SelectionDAG &DAG) {
7596   SDLoc DL(Op);
7597   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7598   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7599   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7600   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7601   ArrayRef<int> Mask = SVOp->getMask();
7602   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7603
7604   // Whenever we can lower this as a zext, that instruction is strictly faster
7605   // than any alternative. It also allows us to fold memory operands into the
7606   // shuffle in many cases.
7607   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7608                                                          Mask, Subtarget, DAG))
7609     return ZExt;
7610
7611   int NumV2Elements =
7612       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7613
7614   if (NumV2Elements == 0) {
7615     // Check for being able to broadcast a single element.
7616     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7617                                                           Mask, Subtarget, DAG))
7618       return Broadcast;
7619
7620     // Straight shuffle of a single input vector. For everything from SSE2
7621     // onward this has a single fast instruction with no scary immediates.
7622     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7623     // but we aren't actually going to use the UNPCK instruction because doing
7624     // so prevents folding a load into this instruction or making a copy.
7625     const int UnpackLoMask[] = {0, 0, 1, 1};
7626     const int UnpackHiMask[] = {2, 2, 3, 3};
7627     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7628       Mask = UnpackLoMask;
7629     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7630       Mask = UnpackHiMask;
7631
7632     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7633                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7634   }
7635
7636   // Try to use shift instructions.
7637   if (SDValue Shift =
7638           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7639     return Shift;
7640
7641   // There are special ways we can lower some single-element blends.
7642   if (NumV2Elements == 1)
7643     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7644                                                          Mask, Subtarget, DAG))
7645       return V;
7646
7647   // We have different paths for blend lowering, but they all must use the
7648   // *exact* same predicate.
7649   bool IsBlendSupported = Subtarget->hasSSE41();
7650   if (IsBlendSupported)
7651     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7652                                                   Subtarget, DAG))
7653       return Blend;
7654
7655   if (SDValue Masked =
7656           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7657     return Masked;
7658
7659   // Use dedicated unpack instructions for masks that match their pattern.
7660   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7661     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7662   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7663     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7664   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7665     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7666   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7667     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7668
7669   // Try to use byte rotation instructions.
7670   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7671   if (Subtarget->hasSSSE3())
7672     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7673             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7674       return Rotate;
7675
7676   // If we have direct support for blends, we should lower by decomposing into
7677   // a permute. That will be faster than the domain cross.
7678   if (IsBlendSupported)
7679     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7680                                                       Mask, DAG);
7681
7682   // Try to lower by permuting the inputs into an unpack instruction.
7683   if (SDValue Unpack =
7684           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7685     return Unpack;
7686
7687   // We implement this with SHUFPS because it can blend from two vectors.
7688   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7689   // up the inputs, bypassing domain shift penalties that we would encur if we
7690   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7691   // relevant.
7692   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7693                      DAG.getVectorShuffle(
7694                          MVT::v4f32, DL,
7695                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7696                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7697 }
7698
7699 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7700 /// shuffle lowering, and the most complex part.
7701 ///
7702 /// The lowering strategy is to try to form pairs of input lanes which are
7703 /// targeted at the same half of the final vector, and then use a dword shuffle
7704 /// to place them onto the right half, and finally unpack the paired lanes into
7705 /// their final position.
7706 ///
7707 /// The exact breakdown of how to form these dword pairs and align them on the
7708 /// correct sides is really tricky. See the comments within the function for
7709 /// more of the details.
7710 ///
7711 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7712 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7713 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7714 /// vector, form the analogous 128-bit 8-element Mask.
7715 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7716     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7717     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7718   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7719   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7720
7721   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7722   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7723   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7724
7725   SmallVector<int, 4> LoInputs;
7726   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7727                [](int M) { return M >= 0; });
7728   std::sort(LoInputs.begin(), LoInputs.end());
7729   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7730   SmallVector<int, 4> HiInputs;
7731   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7732                [](int M) { return M >= 0; });
7733   std::sort(HiInputs.begin(), HiInputs.end());
7734   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7735   int NumLToL =
7736       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7737   int NumHToL = LoInputs.size() - NumLToL;
7738   int NumLToH =
7739       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7740   int NumHToH = HiInputs.size() - NumLToH;
7741   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7742   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7743   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7744   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7745
7746   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7747   // such inputs we can swap two of the dwords across the half mark and end up
7748   // with <=2 inputs to each half in each half. Once there, we can fall through
7749   // to the generic code below. For example:
7750   //
7751   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7752   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7753   //
7754   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7755   // and an existing 2-into-2 on the other half. In this case we may have to
7756   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7757   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7758   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7759   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7760   // half than the one we target for fixing) will be fixed when we re-enter this
7761   // path. We will also combine away any sequence of PSHUFD instructions that
7762   // result into a single instruction. Here is an example of the tricky case:
7763   //
7764   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7765   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7766   //
7767   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7768   //
7769   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7770   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7771   //
7772   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7773   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7774   //
7775   // The result is fine to be handled by the generic logic.
7776   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7777                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7778                           int AOffset, int BOffset) {
7779     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7780            "Must call this with A having 3 or 1 inputs from the A half.");
7781     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7782            "Must call this with B having 1 or 3 inputs from the B half.");
7783     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7784            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7785
7786     // Compute the index of dword with only one word among the three inputs in
7787     // a half by taking the sum of the half with three inputs and subtracting
7788     // the sum of the actual three inputs. The difference is the remaining
7789     // slot.
7790     int ADWord, BDWord;
7791     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7792     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7793     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7794     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7795     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7796     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7797     int TripleNonInputIdx =
7798         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7799     TripleDWord = TripleNonInputIdx / 2;
7800
7801     // We use xor with one to compute the adjacent DWord to whichever one the
7802     // OneInput is in.
7803     OneInputDWord = (OneInput / 2) ^ 1;
7804
7805     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7806     // and BToA inputs. If there is also such a problem with the BToB and AToB
7807     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7808     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7809     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7810     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7811       // Compute how many inputs will be flipped by swapping these DWords. We
7812       // need
7813       // to balance this to ensure we don't form a 3-1 shuffle in the other
7814       // half.
7815       int NumFlippedAToBInputs =
7816           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7817           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7818       int NumFlippedBToBInputs =
7819           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7820           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7821       if ((NumFlippedAToBInputs == 1 &&
7822            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7823           (NumFlippedBToBInputs == 1 &&
7824            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7825         // We choose whether to fix the A half or B half based on whether that
7826         // half has zero flipped inputs. At zero, we may not be able to fix it
7827         // with that half. We also bias towards fixing the B half because that
7828         // will more commonly be the high half, and we have to bias one way.
7829         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7830                                                        ArrayRef<int> Inputs) {
7831           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7832           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7833                                          PinnedIdx ^ 1) != Inputs.end();
7834           // Determine whether the free index is in the flipped dword or the
7835           // unflipped dword based on where the pinned index is. We use this bit
7836           // in an xor to conditionally select the adjacent dword.
7837           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7838           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7839                                              FixFreeIdx) != Inputs.end();
7840           if (IsFixIdxInput == IsFixFreeIdxInput)
7841             FixFreeIdx += 1;
7842           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7843                                         FixFreeIdx) != Inputs.end();
7844           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7845                  "We need to be changing the number of flipped inputs!");
7846           int PSHUFHalfMask[] = {0, 1, 2, 3};
7847           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7848           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7849                           MVT::v8i16, V,
7850                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7851
7852           for (int &M : Mask)
7853             if (M != -1 && M == FixIdx)
7854               M = FixFreeIdx;
7855             else if (M != -1 && M == FixFreeIdx)
7856               M = FixIdx;
7857         };
7858         if (NumFlippedBToBInputs != 0) {
7859           int BPinnedIdx =
7860               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7861           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7862         } else {
7863           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7864           int APinnedIdx =
7865               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7866           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7867         }
7868       }
7869     }
7870
7871     int PSHUFDMask[] = {0, 1, 2, 3};
7872     PSHUFDMask[ADWord] = BDWord;
7873     PSHUFDMask[BDWord] = ADWord;
7874     V = DAG.getNode(ISD::BITCAST, DL, VT,
7875                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
7876                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
7877                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7878
7879     // Adjust the mask to match the new locations of A and B.
7880     for (int &M : Mask)
7881       if (M != -1 && M/2 == ADWord)
7882         M = 2 * BDWord + M % 2;
7883       else if (M != -1 && M/2 == BDWord)
7884         M = 2 * ADWord + M % 2;
7885
7886     // Recurse back into this routine to re-compute state now that this isn't
7887     // a 3 and 1 problem.
7888     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
7889                                                      DAG);
7890   };
7891   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7892     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7893   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7894     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7895
7896   // At this point there are at most two inputs to the low and high halves from
7897   // each half. That means the inputs can always be grouped into dwords and
7898   // those dwords can then be moved to the correct half with a dword shuffle.
7899   // We use at most one low and one high word shuffle to collect these paired
7900   // inputs into dwords, and finally a dword shuffle to place them.
7901   int PSHUFLMask[4] = {-1, -1, -1, -1};
7902   int PSHUFHMask[4] = {-1, -1, -1, -1};
7903   int PSHUFDMask[4] = {-1, -1, -1, -1};
7904
7905   // First fix the masks for all the inputs that are staying in their
7906   // original halves. This will then dictate the targets of the cross-half
7907   // shuffles.
7908   auto fixInPlaceInputs =
7909       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7910                     MutableArrayRef<int> SourceHalfMask,
7911                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7912     if (InPlaceInputs.empty())
7913       return;
7914     if (InPlaceInputs.size() == 1) {
7915       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7916           InPlaceInputs[0] - HalfOffset;
7917       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7918       return;
7919     }
7920     if (IncomingInputs.empty()) {
7921       // Just fix all of the in place inputs.
7922       for (int Input : InPlaceInputs) {
7923         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7924         PSHUFDMask[Input / 2] = Input / 2;
7925       }
7926       return;
7927     }
7928
7929     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7930     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7931         InPlaceInputs[0] - HalfOffset;
7932     // Put the second input next to the first so that they are packed into
7933     // a dword. We find the adjacent index by toggling the low bit.
7934     int AdjIndex = InPlaceInputs[0] ^ 1;
7935     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7936     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7937     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7938   };
7939   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7940   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7941
7942   // Now gather the cross-half inputs and place them into a free dword of
7943   // their target half.
7944   // FIXME: This operation could almost certainly be simplified dramatically to
7945   // look more like the 3-1 fixing operation.
7946   auto moveInputsToRightHalf = [&PSHUFDMask](
7947       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7948       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7949       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7950       int DestOffset) {
7951     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7952       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7953     };
7954     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7955                                                int Word) {
7956       int LowWord = Word & ~1;
7957       int HighWord = Word | 1;
7958       return isWordClobbered(SourceHalfMask, LowWord) ||
7959              isWordClobbered(SourceHalfMask, HighWord);
7960     };
7961
7962     if (IncomingInputs.empty())
7963       return;
7964
7965     if (ExistingInputs.empty()) {
7966       // Map any dwords with inputs from them into the right half.
7967       for (int Input : IncomingInputs) {
7968         // If the source half mask maps over the inputs, turn those into
7969         // swaps and use the swapped lane.
7970         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7971           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7972             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7973                 Input - SourceOffset;
7974             // We have to swap the uses in our half mask in one sweep.
7975             for (int &M : HalfMask)
7976               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7977                 M = Input;
7978               else if (M == Input)
7979                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7980           } else {
7981             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7982                        Input - SourceOffset &&
7983                    "Previous placement doesn't match!");
7984           }
7985           // Note that this correctly re-maps both when we do a swap and when
7986           // we observe the other side of the swap above. We rely on that to
7987           // avoid swapping the members of the input list directly.
7988           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7989         }
7990
7991         // Map the input's dword into the correct half.
7992         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7993           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7994         else
7995           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7996                      Input / 2 &&
7997                  "Previous placement doesn't match!");
7998       }
7999
8000       // And just directly shift any other-half mask elements to be same-half
8001       // as we will have mirrored the dword containing the element into the
8002       // same position within that half.
8003       for (int &M : HalfMask)
8004         if (M >= SourceOffset && M < SourceOffset + 4) {
8005           M = M - SourceOffset + DestOffset;
8006           assert(M >= 0 && "This should never wrap below zero!");
8007         }
8008       return;
8009     }
8010
8011     // Ensure we have the input in a viable dword of its current half. This
8012     // is particularly tricky because the original position may be clobbered
8013     // by inputs being moved and *staying* in that half.
8014     if (IncomingInputs.size() == 1) {
8015       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8016         int InputFixed = std::find(std::begin(SourceHalfMask),
8017                                    std::end(SourceHalfMask), -1) -
8018                          std::begin(SourceHalfMask) + SourceOffset;
8019         SourceHalfMask[InputFixed - SourceOffset] =
8020             IncomingInputs[0] - SourceOffset;
8021         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8022                      InputFixed);
8023         IncomingInputs[0] = InputFixed;
8024       }
8025     } else if (IncomingInputs.size() == 2) {
8026       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8027           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8028         // We have two non-adjacent or clobbered inputs we need to extract from
8029         // the source half. To do this, we need to map them into some adjacent
8030         // dword slot in the source mask.
8031         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8032                               IncomingInputs[1] - SourceOffset};
8033
8034         // If there is a free slot in the source half mask adjacent to one of
8035         // the inputs, place the other input in it. We use (Index XOR 1) to
8036         // compute an adjacent index.
8037         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8038             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8039           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8040           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8041           InputsFixed[1] = InputsFixed[0] ^ 1;
8042         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8043                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8044           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8045           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8046           InputsFixed[0] = InputsFixed[1] ^ 1;
8047         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8048                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8049           // The two inputs are in the same DWord but it is clobbered and the
8050           // adjacent DWord isn't used at all. Move both inputs to the free
8051           // slot.
8052           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8053           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8054           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8055           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8056         } else {
8057           // The only way we hit this point is if there is no clobbering
8058           // (because there are no off-half inputs to this half) and there is no
8059           // free slot adjacent to one of the inputs. In this case, we have to
8060           // swap an input with a non-input.
8061           for (int i = 0; i < 4; ++i)
8062             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8063                    "We can't handle any clobbers here!");
8064           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8065                  "Cannot have adjacent inputs here!");
8066
8067           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8068           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8069
8070           // We also have to update the final source mask in this case because
8071           // it may need to undo the above swap.
8072           for (int &M : FinalSourceHalfMask)
8073             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8074               M = InputsFixed[1] + SourceOffset;
8075             else if (M == InputsFixed[1] + SourceOffset)
8076               M = (InputsFixed[0] ^ 1) + SourceOffset;
8077
8078           InputsFixed[1] = InputsFixed[0] ^ 1;
8079         }
8080
8081         // Point everything at the fixed inputs.
8082         for (int &M : HalfMask)
8083           if (M == IncomingInputs[0])
8084             M = InputsFixed[0] + SourceOffset;
8085           else if (M == IncomingInputs[1])
8086             M = InputsFixed[1] + SourceOffset;
8087
8088         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8089         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8090       }
8091     } else {
8092       llvm_unreachable("Unhandled input size!");
8093     }
8094
8095     // Now hoist the DWord down to the right half.
8096     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8097     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8098     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8099     for (int &M : HalfMask)
8100       for (int Input : IncomingInputs)
8101         if (M == Input)
8102           M = FreeDWord * 2 + Input % 2;
8103   };
8104   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8105                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8106   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8107                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8108
8109   // Now enact all the shuffles we've computed to move the inputs into their
8110   // target half.
8111   if (!isNoopShuffleMask(PSHUFLMask))
8112     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8113                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8114   if (!isNoopShuffleMask(PSHUFHMask))
8115     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8116                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8117   if (!isNoopShuffleMask(PSHUFDMask))
8118     V = DAG.getNode(ISD::BITCAST, DL, VT,
8119                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8120                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8121                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8122
8123   // At this point, each half should contain all its inputs, and we can then
8124   // just shuffle them into their final position.
8125   assert(std::count_if(LoMask.begin(), LoMask.end(),
8126                        [](int M) { return M >= 4; }) == 0 &&
8127          "Failed to lift all the high half inputs to the low mask!");
8128   assert(std::count_if(HiMask.begin(), HiMask.end(),
8129                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8130          "Failed to lift all the low half inputs to the high mask!");
8131
8132   // Do a half shuffle for the low mask.
8133   if (!isNoopShuffleMask(LoMask))
8134     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8135                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8136
8137   // Do a half shuffle with the high mask after shifting its values down.
8138   for (int &M : HiMask)
8139     if (M >= 0)
8140       M -= 4;
8141   if (!isNoopShuffleMask(HiMask))
8142     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8143                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8144
8145   return V;
8146 }
8147
8148 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8149 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8150                                           SDValue V2, ArrayRef<int> Mask,
8151                                           SelectionDAG &DAG, bool &V1InUse,
8152                                           bool &V2InUse) {
8153   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8154   SDValue V1Mask[16];
8155   SDValue V2Mask[16];
8156   V1InUse = false;
8157   V2InUse = false;
8158
8159   int Size = Mask.size();
8160   int Scale = 16 / Size;
8161   for (int i = 0; i < 16; ++i) {
8162     if (Mask[i / Scale] == -1) {
8163       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8164     } else {
8165       const int ZeroMask = 0x80;
8166       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8167                                           : ZeroMask;
8168       int V2Idx = Mask[i / Scale] < Size
8169                       ? ZeroMask
8170                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8171       if (Zeroable[i / Scale])
8172         V1Idx = V2Idx = ZeroMask;
8173       V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8174       V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8175       V1InUse |= (ZeroMask != V1Idx);
8176       V2InUse |= (ZeroMask != V2Idx);
8177     }
8178   }
8179
8180   if (V1InUse)
8181     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8182                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8183                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8184   if (V2InUse)
8185     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8186                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8187                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8188
8189   // If we need shuffled inputs from both, blend the two.
8190   SDValue V;
8191   if (V1InUse && V2InUse)
8192     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8193   else
8194     V = V1InUse ? V1 : V2;
8195
8196   // Cast the result back to the correct type.
8197   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8198 }
8199
8200 /// \brief Generic lowering of 8-lane i16 shuffles.
8201 ///
8202 /// This handles both single-input shuffles and combined shuffle/blends with
8203 /// two inputs. The single input shuffles are immediately delegated to
8204 /// a dedicated lowering routine.
8205 ///
8206 /// The blends are lowered in one of three fundamental ways. If there are few
8207 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8208 /// of the input is significantly cheaper when lowered as an interleaving of
8209 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8210 /// halves of the inputs separately (making them have relatively few inputs)
8211 /// and then concatenate them.
8212 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8213                                        const X86Subtarget *Subtarget,
8214                                        SelectionDAG &DAG) {
8215   SDLoc DL(Op);
8216   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8217   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8218   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8219   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8220   ArrayRef<int> OrigMask = SVOp->getMask();
8221   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8222                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8223   MutableArrayRef<int> Mask(MaskStorage);
8224
8225   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8226
8227   // Whenever we can lower this as a zext, that instruction is strictly faster
8228   // than any alternative.
8229   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8230           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8231     return ZExt;
8232
8233   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8234   (void)isV1;
8235   auto isV2 = [](int M) { return M >= 8; };
8236
8237   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8238
8239   if (NumV2Inputs == 0) {
8240     // Check for being able to broadcast a single element.
8241     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8242                                                           Mask, Subtarget, DAG))
8243       return Broadcast;
8244
8245     // Try to use shift instructions.
8246     if (SDValue Shift =
8247             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8248       return Shift;
8249
8250     // Use dedicated unpack instructions for masks that match their pattern.
8251     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8252       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8253     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8254       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8255
8256     // Try to use byte rotation instructions.
8257     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8258                                                         Mask, Subtarget, DAG))
8259       return Rotate;
8260
8261     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8262                                                      Subtarget, DAG);
8263   }
8264
8265   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8266          "All single-input shuffles should be canonicalized to be V1-input "
8267          "shuffles.");
8268
8269   // Try to use shift instructions.
8270   if (SDValue Shift =
8271           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8272     return Shift;
8273
8274   // There are special ways we can lower some single-element blends.
8275   if (NumV2Inputs == 1)
8276     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8277                                                          Mask, Subtarget, DAG))
8278       return V;
8279
8280   // We have different paths for blend lowering, but they all must use the
8281   // *exact* same predicate.
8282   bool IsBlendSupported = Subtarget->hasSSE41();
8283   if (IsBlendSupported)
8284     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8285                                                   Subtarget, DAG))
8286       return Blend;
8287
8288   if (SDValue Masked =
8289           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8290     return Masked;
8291
8292   // Use dedicated unpack instructions for masks that match their pattern.
8293   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8294     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8295   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8296     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8297
8298   // Try to use byte rotation instructions.
8299   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8300           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8301     return Rotate;
8302
8303   if (SDValue BitBlend =
8304           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8305     return BitBlend;
8306
8307   if (SDValue Unpack =
8308           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8309     return Unpack;
8310
8311   // If we can't directly blend but can use PSHUFB, that will be better as it
8312   // can both shuffle and set up the inefficient blend.
8313   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8314     bool V1InUse, V2InUse;
8315     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8316                                       V1InUse, V2InUse);
8317   }
8318
8319   // We can always bit-blend if we have to so the fallback strategy is to
8320   // decompose into single-input permutes and blends.
8321   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8322                                                       Mask, DAG);
8323 }
8324
8325 /// \brief Check whether a compaction lowering can be done by dropping even
8326 /// elements and compute how many times even elements must be dropped.
8327 ///
8328 /// This handles shuffles which take every Nth element where N is a power of
8329 /// two. Example shuffle masks:
8330 ///
8331 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8332 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8333 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8334 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8335 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8336 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8337 ///
8338 /// Any of these lanes can of course be undef.
8339 ///
8340 /// This routine only supports N <= 3.
8341 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8342 /// for larger N.
8343 ///
8344 /// \returns N above, or the number of times even elements must be dropped if
8345 /// there is such a number. Otherwise returns zero.
8346 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8347   // Figure out whether we're looping over two inputs or just one.
8348   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8349
8350   // The modulus for the shuffle vector entries is based on whether this is
8351   // a single input or not.
8352   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8353   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8354          "We should only be called with masks with a power-of-2 size!");
8355
8356   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8357
8358   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8359   // and 2^3 simultaneously. This is because we may have ambiguity with
8360   // partially undef inputs.
8361   bool ViableForN[3] = {true, true, true};
8362
8363   for (int i = 0, e = Mask.size(); i < e; ++i) {
8364     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8365     // want.
8366     if (Mask[i] == -1)
8367       continue;
8368
8369     bool IsAnyViable = false;
8370     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8371       if (ViableForN[j]) {
8372         uint64_t N = j + 1;
8373
8374         // The shuffle mask must be equal to (i * 2^N) % M.
8375         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8376           IsAnyViable = true;
8377         else
8378           ViableForN[j] = false;
8379       }
8380     // Early exit if we exhaust the possible powers of two.
8381     if (!IsAnyViable)
8382       break;
8383   }
8384
8385   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8386     if (ViableForN[j])
8387       return j + 1;
8388
8389   // Return 0 as there is no viable power of two.
8390   return 0;
8391 }
8392
8393 /// \brief Generic lowering of v16i8 shuffles.
8394 ///
8395 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8396 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8397 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8398 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8399 /// back together.
8400 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8401                                        const X86Subtarget *Subtarget,
8402                                        SelectionDAG &DAG) {
8403   SDLoc DL(Op);
8404   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8405   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8406   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8407   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8408   ArrayRef<int> Mask = SVOp->getMask();
8409   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8410
8411   // Try to use shift instructions.
8412   if (SDValue Shift =
8413           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8414     return Shift;
8415
8416   // Try to use byte rotation instructions.
8417   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8418           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8419     return Rotate;
8420
8421   // Try to use a zext lowering.
8422   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8423           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8424     return ZExt;
8425
8426   int NumV2Elements =
8427       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8428
8429   // For single-input shuffles, there are some nicer lowering tricks we can use.
8430   if (NumV2Elements == 0) {
8431     // Check for being able to broadcast a single element.
8432     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8433                                                           Mask, Subtarget, DAG))
8434       return Broadcast;
8435
8436     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8437     // Notably, this handles splat and partial-splat shuffles more efficiently.
8438     // However, it only makes sense if the pre-duplication shuffle simplifies
8439     // things significantly. Currently, this means we need to be able to
8440     // express the pre-duplication shuffle as an i16 shuffle.
8441     //
8442     // FIXME: We should check for other patterns which can be widened into an
8443     // i16 shuffle as well.
8444     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8445       for (int i = 0; i < 16; i += 2)
8446         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8447           return false;
8448
8449       return true;
8450     };
8451     auto tryToWidenViaDuplication = [&]() -> SDValue {
8452       if (!canWidenViaDuplication(Mask))
8453         return SDValue();
8454       SmallVector<int, 4> LoInputs;
8455       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8456                    [](int M) { return M >= 0 && M < 8; });
8457       std::sort(LoInputs.begin(), LoInputs.end());
8458       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8459                      LoInputs.end());
8460       SmallVector<int, 4> HiInputs;
8461       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8462                    [](int M) { return M >= 8; });
8463       std::sort(HiInputs.begin(), HiInputs.end());
8464       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8465                      HiInputs.end());
8466
8467       bool TargetLo = LoInputs.size() >= HiInputs.size();
8468       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8469       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8470
8471       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8472       SmallDenseMap<int, int, 8> LaneMap;
8473       for (int I : InPlaceInputs) {
8474         PreDupI16Shuffle[I/2] = I/2;
8475         LaneMap[I] = I;
8476       }
8477       int j = TargetLo ? 0 : 4, je = j + 4;
8478       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8479         // Check if j is already a shuffle of this input. This happens when
8480         // there are two adjacent bytes after we move the low one.
8481         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8482           // If we haven't yet mapped the input, search for a slot into which
8483           // we can map it.
8484           while (j < je && PreDupI16Shuffle[j] != -1)
8485             ++j;
8486
8487           if (j == je)
8488             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8489             return SDValue();
8490
8491           // Map this input with the i16 shuffle.
8492           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8493         }
8494
8495         // Update the lane map based on the mapping we ended up with.
8496         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8497       }
8498       V1 = DAG.getNode(
8499           ISD::BITCAST, DL, MVT::v16i8,
8500           DAG.getVectorShuffle(MVT::v8i16, DL,
8501                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8502                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8503
8504       // Unpack the bytes to form the i16s that will be shuffled into place.
8505       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8506                        MVT::v16i8, V1, V1);
8507
8508       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8509       for (int i = 0; i < 16; ++i)
8510         if (Mask[i] != -1) {
8511           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8512           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8513           if (PostDupI16Shuffle[i / 2] == -1)
8514             PostDupI16Shuffle[i / 2] = MappedMask;
8515           else
8516             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8517                    "Conflicting entrties in the original shuffle!");
8518         }
8519       return DAG.getNode(
8520           ISD::BITCAST, DL, MVT::v16i8,
8521           DAG.getVectorShuffle(MVT::v8i16, DL,
8522                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8523                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8524     };
8525     if (SDValue V = tryToWidenViaDuplication())
8526       return V;
8527   }
8528
8529   // Use dedicated unpack instructions for masks that match their pattern.
8530   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8531                                          0, 16, 1, 17, 2, 18, 3, 19,
8532                                          // High half.
8533                                          4, 20, 5, 21, 6, 22, 7, 23}))
8534     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8535   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8536                                          8, 24, 9, 25, 10, 26, 11, 27,
8537                                          // High half.
8538                                          12, 28, 13, 29, 14, 30, 15, 31}))
8539     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8540
8541   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8542   // with PSHUFB. It is important to do this before we attempt to generate any
8543   // blends but after all of the single-input lowerings. If the single input
8544   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8545   // want to preserve that and we can DAG combine any longer sequences into
8546   // a PSHUFB in the end. But once we start blending from multiple inputs,
8547   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8548   // and there are *very* few patterns that would actually be faster than the
8549   // PSHUFB approach because of its ability to zero lanes.
8550   //
8551   // FIXME: The only exceptions to the above are blends which are exact
8552   // interleavings with direct instructions supporting them. We currently don't
8553   // handle those well here.
8554   if (Subtarget->hasSSSE3()) {
8555     bool V1InUse = false;
8556     bool V2InUse = false;
8557
8558     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8559                                                 DAG, V1InUse, V2InUse);
8560
8561     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8562     // do so. This avoids using them to handle blends-with-zero which is
8563     // important as a single pshufb is significantly faster for that.
8564     if (V1InUse && V2InUse) {
8565       if (Subtarget->hasSSE41())
8566         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8567                                                       Mask, Subtarget, DAG))
8568           return Blend;
8569
8570       // We can use an unpack to do the blending rather than an or in some
8571       // cases. Even though the or may be (very minorly) more efficient, we
8572       // preference this lowering because there are common cases where part of
8573       // the complexity of the shuffles goes away when we do the final blend as
8574       // an unpack.
8575       // FIXME: It might be worth trying to detect if the unpack-feeding
8576       // shuffles will both be pshufb, in which case we shouldn't bother with
8577       // this.
8578       if (SDValue Unpack =
8579               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8580         return Unpack;
8581     }
8582
8583     return PSHUFB;
8584   }
8585
8586   // There are special ways we can lower some single-element blends.
8587   if (NumV2Elements == 1)
8588     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8589                                                          Mask, Subtarget, DAG))
8590       return V;
8591
8592   if (SDValue BitBlend =
8593           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8594     return BitBlend;
8595
8596   // Check whether a compaction lowering can be done. This handles shuffles
8597   // which take every Nth element for some even N. See the helper function for
8598   // details.
8599   //
8600   // We special case these as they can be particularly efficiently handled with
8601   // the PACKUSB instruction on x86 and they show up in common patterns of
8602   // rearranging bytes to truncate wide elements.
8603   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8604     // NumEvenDrops is the power of two stride of the elements. Another way of
8605     // thinking about it is that we need to drop the even elements this many
8606     // times to get the original input.
8607     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8608
8609     // First we need to zero all the dropped bytes.
8610     assert(NumEvenDrops <= 3 &&
8611            "No support for dropping even elements more than 3 times.");
8612     // We use the mask type to pick which bytes are preserved based on how many
8613     // elements are dropped.
8614     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8615     SDValue ByteClearMask =
8616         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8617                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8618     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8619     if (!IsSingleInput)
8620       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8621
8622     // Now pack things back together.
8623     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8624     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8625     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8626     for (int i = 1; i < NumEvenDrops; ++i) {
8627       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8628       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8629     }
8630
8631     return Result;
8632   }
8633
8634   // Handle multi-input cases by blending single-input shuffles.
8635   if (NumV2Elements > 0)
8636     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8637                                                       Mask, DAG);
8638
8639   // The fallback path for single-input shuffles widens this into two v8i16
8640   // vectors with unpacks, shuffles those, and then pulls them back together
8641   // with a pack.
8642   SDValue V = V1;
8643
8644   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8645   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8646   for (int i = 0; i < 16; ++i)
8647     if (Mask[i] >= 0)
8648       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8649
8650   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8651
8652   SDValue VLoHalf, VHiHalf;
8653   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8654   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8655   // i16s.
8656   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8657                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8658       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8659                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8660     // Use a mask to drop the high bytes.
8661     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8662     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8663                      DAG.getConstant(0x00FF, MVT::v8i16));
8664
8665     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8666     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8667
8668     // Squash the masks to point directly into VLoHalf.
8669     for (int &M : LoBlendMask)
8670       if (M >= 0)
8671         M /= 2;
8672     for (int &M : HiBlendMask)
8673       if (M >= 0)
8674         M /= 2;
8675   } else {
8676     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8677     // VHiHalf so that we can blend them as i16s.
8678     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8679                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8680     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8681                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8682   }
8683
8684   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8685   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8686
8687   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8688 }
8689
8690 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8691 ///
8692 /// This routine breaks down the specific type of 128-bit shuffle and
8693 /// dispatches to the lowering routines accordingly.
8694 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8695                                         MVT VT, const X86Subtarget *Subtarget,
8696                                         SelectionDAG &DAG) {
8697   switch (VT.SimpleTy) {
8698   case MVT::v2i64:
8699     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8700   case MVT::v2f64:
8701     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8702   case MVT::v4i32:
8703     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8704   case MVT::v4f32:
8705     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8706   case MVT::v8i16:
8707     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8708   case MVT::v16i8:
8709     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8710
8711   default:
8712     llvm_unreachable("Unimplemented!");
8713   }
8714 }
8715
8716 /// \brief Helper function to test whether a shuffle mask could be
8717 /// simplified by widening the elements being shuffled.
8718 ///
8719 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8720 /// leaves it in an unspecified state.
8721 ///
8722 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8723 /// shuffle masks. The latter have the special property of a '-2' representing
8724 /// a zero-ed lane of a vector.
8725 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8726                                     SmallVectorImpl<int> &WidenedMask) {
8727   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8728     // If both elements are undef, its trivial.
8729     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8730       WidenedMask.push_back(SM_SentinelUndef);
8731       continue;
8732     }
8733
8734     // Check for an undef mask and a mask value properly aligned to fit with
8735     // a pair of values. If we find such a case, use the non-undef mask's value.
8736     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8737       WidenedMask.push_back(Mask[i + 1] / 2);
8738       continue;
8739     }
8740     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8741       WidenedMask.push_back(Mask[i] / 2);
8742       continue;
8743     }
8744
8745     // When zeroing, we need to spread the zeroing across both lanes to widen.
8746     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8747       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8748           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8749         WidenedMask.push_back(SM_SentinelZero);
8750         continue;
8751       }
8752       return false;
8753     }
8754
8755     // Finally check if the two mask values are adjacent and aligned with
8756     // a pair.
8757     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8758       WidenedMask.push_back(Mask[i] / 2);
8759       continue;
8760     }
8761
8762     // Otherwise we can't safely widen the elements used in this shuffle.
8763     return false;
8764   }
8765   assert(WidenedMask.size() == Mask.size() / 2 &&
8766          "Incorrect size of mask after widening the elements!");
8767
8768   return true;
8769 }
8770
8771 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8772 ///
8773 /// This routine just extracts two subvectors, shuffles them independently, and
8774 /// then concatenates them back together. This should work effectively with all
8775 /// AVX vector shuffle types.
8776 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8777                                           SDValue V2, ArrayRef<int> Mask,
8778                                           SelectionDAG &DAG) {
8779   assert(VT.getSizeInBits() >= 256 &&
8780          "Only for 256-bit or wider vector shuffles!");
8781   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8782   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8783
8784   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8785   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8786
8787   int NumElements = VT.getVectorNumElements();
8788   int SplitNumElements = NumElements / 2;
8789   MVT ScalarVT = VT.getScalarType();
8790   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8791
8792   // Rather than splitting build-vectors, just build two narrower build
8793   // vectors. This helps shuffling with splats and zeros.
8794   auto SplitVector = [&](SDValue V) {
8795     while (V.getOpcode() == ISD::BITCAST)
8796       V = V->getOperand(0);
8797
8798     MVT OrigVT = V.getSimpleValueType();
8799     int OrigNumElements = OrigVT.getVectorNumElements();
8800     int OrigSplitNumElements = OrigNumElements / 2;
8801     MVT OrigScalarVT = OrigVT.getScalarType();
8802     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8803
8804     SDValue LoV, HiV;
8805
8806     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8807     if (!BV) {
8808       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8809                         DAG.getIntPtrConstant(0));
8810       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8811                         DAG.getIntPtrConstant(OrigSplitNumElements));
8812     } else {
8813
8814       SmallVector<SDValue, 16> LoOps, HiOps;
8815       for (int i = 0; i < OrigSplitNumElements; ++i) {
8816         LoOps.push_back(BV->getOperand(i));
8817         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8818       }
8819       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8820       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8821     }
8822     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8823                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8824   };
8825
8826   SDValue LoV1, HiV1, LoV2, HiV2;
8827   std::tie(LoV1, HiV1) = SplitVector(V1);
8828   std::tie(LoV2, HiV2) = SplitVector(V2);
8829
8830   // Now create two 4-way blends of these half-width vectors.
8831   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8832     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8833     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8834     for (int i = 0; i < SplitNumElements; ++i) {
8835       int M = HalfMask[i];
8836       if (M >= NumElements) {
8837         if (M >= NumElements + SplitNumElements)
8838           UseHiV2 = true;
8839         else
8840           UseLoV2 = true;
8841         V2BlendMask.push_back(M - NumElements);
8842         V1BlendMask.push_back(-1);
8843         BlendMask.push_back(SplitNumElements + i);
8844       } else if (M >= 0) {
8845         if (M >= SplitNumElements)
8846           UseHiV1 = true;
8847         else
8848           UseLoV1 = true;
8849         V2BlendMask.push_back(-1);
8850         V1BlendMask.push_back(M);
8851         BlendMask.push_back(i);
8852       } else {
8853         V2BlendMask.push_back(-1);
8854         V1BlendMask.push_back(-1);
8855         BlendMask.push_back(-1);
8856       }
8857     }
8858
8859     // Because the lowering happens after all combining takes place, we need to
8860     // manually combine these blend masks as much as possible so that we create
8861     // a minimal number of high-level vector shuffle nodes.
8862
8863     // First try just blending the halves of V1 or V2.
8864     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8865       return DAG.getUNDEF(SplitVT);
8866     if (!UseLoV2 && !UseHiV2)
8867       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8868     if (!UseLoV1 && !UseHiV1)
8869       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8870
8871     SDValue V1Blend, V2Blend;
8872     if (UseLoV1 && UseHiV1) {
8873       V1Blend =
8874         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8875     } else {
8876       // We only use half of V1 so map the usage down into the final blend mask.
8877       V1Blend = UseLoV1 ? LoV1 : HiV1;
8878       for (int i = 0; i < SplitNumElements; ++i)
8879         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8880           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8881     }
8882     if (UseLoV2 && UseHiV2) {
8883       V2Blend =
8884         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8885     } else {
8886       // We only use half of V2 so map the usage down into the final blend mask.
8887       V2Blend = UseLoV2 ? LoV2 : HiV2;
8888       for (int i = 0; i < SplitNumElements; ++i)
8889         if (BlendMask[i] >= SplitNumElements)
8890           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8891     }
8892     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8893   };
8894   SDValue Lo = HalfBlend(LoMask);
8895   SDValue Hi = HalfBlend(HiMask);
8896   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8897 }
8898
8899 /// \brief Either split a vector in halves or decompose the shuffles and the
8900 /// blend.
8901 ///
8902 /// This is provided as a good fallback for many lowerings of non-single-input
8903 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8904 /// between splitting the shuffle into 128-bit components and stitching those
8905 /// back together vs. extracting the single-input shuffles and blending those
8906 /// results.
8907 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8908                                                 SDValue V2, ArrayRef<int> Mask,
8909                                                 SelectionDAG &DAG) {
8910   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8911                                             "lower single-input shuffles as it "
8912                                             "could then recurse on itself.");
8913   int Size = Mask.size();
8914
8915   // If this can be modeled as a broadcast of two elements followed by a blend,
8916   // prefer that lowering. This is especially important because broadcasts can
8917   // often fold with memory operands.
8918   auto DoBothBroadcast = [&] {
8919     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8920     for (int M : Mask)
8921       if (M >= Size) {
8922         if (V2BroadcastIdx == -1)
8923           V2BroadcastIdx = M - Size;
8924         else if (M - Size != V2BroadcastIdx)
8925           return false;
8926       } else if (M >= 0) {
8927         if (V1BroadcastIdx == -1)
8928           V1BroadcastIdx = M;
8929         else if (M != V1BroadcastIdx)
8930           return false;
8931       }
8932     return true;
8933   };
8934   if (DoBothBroadcast())
8935     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8936                                                       DAG);
8937
8938   // If the inputs all stem from a single 128-bit lane of each input, then we
8939   // split them rather than blending because the split will decompose to
8940   // unusually few instructions.
8941   int LaneCount = VT.getSizeInBits() / 128;
8942   int LaneSize = Size / LaneCount;
8943   SmallBitVector LaneInputs[2];
8944   LaneInputs[0].resize(LaneCount, false);
8945   LaneInputs[1].resize(LaneCount, false);
8946   for (int i = 0; i < Size; ++i)
8947     if (Mask[i] >= 0)
8948       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8949   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8950     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8951
8952   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8953   // that the decomposed single-input shuffles don't end up here.
8954   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8955 }
8956
8957 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
8958 /// a permutation and blend of those lanes.
8959 ///
8960 /// This essentially blends the out-of-lane inputs to each lane into the lane
8961 /// from a permuted copy of the vector. This lowering strategy results in four
8962 /// instructions in the worst case for a single-input cross lane shuffle which
8963 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
8964 /// of. Special cases for each particular shuffle pattern should be handled
8965 /// prior to trying this lowering.
8966 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
8967                                                        SDValue V1, SDValue V2,
8968                                                        ArrayRef<int> Mask,
8969                                                        SelectionDAG &DAG) {
8970   // FIXME: This should probably be generalized for 512-bit vectors as well.
8971   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8972   int LaneSize = Mask.size() / 2;
8973
8974   // If there are only inputs from one 128-bit lane, splitting will in fact be
8975   // less expensive. The flags track whether the given lane contains an element
8976   // that crosses to another lane.
8977   bool LaneCrossing[2] = {false, false};
8978   for (int i = 0, Size = Mask.size(); i < Size; ++i)
8979     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
8980       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
8981   if (!LaneCrossing[0] || !LaneCrossing[1])
8982     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8983
8984   if (isSingleInputShuffleMask(Mask)) {
8985     SmallVector<int, 32> FlippedBlendMask;
8986     for (int i = 0, Size = Mask.size(); i < Size; ++i)
8987       FlippedBlendMask.push_back(
8988           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
8989                                   ? Mask[i]
8990                                   : Mask[i] % LaneSize +
8991                                         (i / LaneSize) * LaneSize + Size));
8992
8993     // Flip the vector, and blend the results which should now be in-lane. The
8994     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
8995     // 5 for the high source. The value 3 selects the high half of source 2 and
8996     // the value 2 selects the low half of source 2. We only use source 2 to
8997     // allow folding it into a memory operand.
8998     unsigned PERMMask = 3 | 2 << 4;
8999     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9000                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9001     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9002   }
9003
9004   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9005   // will be handled by the above logic and a blend of the results, much like
9006   // other patterns in AVX.
9007   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9008 }
9009
9010 /// \brief Handle lowering 2-lane 128-bit shuffles.
9011 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9012                                         SDValue V2, ArrayRef<int> Mask,
9013                                         const X86Subtarget *Subtarget,
9014                                         SelectionDAG &DAG) {
9015   // Blends are faster and handle all the non-lane-crossing cases.
9016   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9017                                                 Subtarget, DAG))
9018     return Blend;
9019
9020   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9021                                VT.getVectorNumElements() / 2);
9022   // Check for patterns which can be matched with a single insert of a 128-bit
9023   // subvector.
9024   bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9025   if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9026     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9027                               DAG.getIntPtrConstant(0));
9028     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9029                               OnlyUsesV1 ? V1 : V2, DAG.getIntPtrConstant(0));
9030     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9031   }
9032   if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 6, 7})) {
9033     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9034                               DAG.getIntPtrConstant(0));
9035     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9036                               DAG.getIntPtrConstant(2));
9037     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9038   }
9039
9040   // Otherwise form a 128-bit permutation.
9041   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9042   int MaskLO = Mask[0];
9043   if (MaskLO == SM_SentinelUndef)
9044     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9045
9046   int MaskHI = Mask[2];
9047   if (MaskHI == SM_SentinelUndef)
9048     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9049
9050   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9051   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9052                      DAG.getConstant(PermMask, MVT::i8));
9053 }
9054
9055 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9056 /// shuffling each lane.
9057 ///
9058 /// This will only succeed when the result of fixing the 128-bit lanes results
9059 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9060 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9061 /// the lane crosses early and then use simpler shuffles within each lane.
9062 ///
9063 /// FIXME: It might be worthwhile at some point to support this without
9064 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9065 /// in x86 only floating point has interesting non-repeating shuffles, and even
9066 /// those are still *marginally* more expensive.
9067 static SDValue lowerVectorShuffleByMerging128BitLanes(
9068     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9069     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9070   assert(!isSingleInputShuffleMask(Mask) &&
9071          "This is only useful with multiple inputs.");
9072
9073   int Size = Mask.size();
9074   int LaneSize = 128 / VT.getScalarSizeInBits();
9075   int NumLanes = Size / LaneSize;
9076   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9077
9078   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9079   // check whether the in-128-bit lane shuffles share a repeating pattern.
9080   SmallVector<int, 4> Lanes;
9081   Lanes.resize(NumLanes, -1);
9082   SmallVector<int, 4> InLaneMask;
9083   InLaneMask.resize(LaneSize, -1);
9084   for (int i = 0; i < Size; ++i) {
9085     if (Mask[i] < 0)
9086       continue;
9087
9088     int j = i / LaneSize;
9089
9090     if (Lanes[j] < 0) {
9091       // First entry we've seen for this lane.
9092       Lanes[j] = Mask[i] / LaneSize;
9093     } else if (Lanes[j] != Mask[i] / LaneSize) {
9094       // This doesn't match the lane selected previously!
9095       return SDValue();
9096     }
9097
9098     // Check that within each lane we have a consistent shuffle mask.
9099     int k = i % LaneSize;
9100     if (InLaneMask[k] < 0) {
9101       InLaneMask[k] = Mask[i] % LaneSize;
9102     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9103       // This doesn't fit a repeating in-lane mask.
9104       return SDValue();
9105     }
9106   }
9107
9108   // First shuffle the lanes into place.
9109   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9110                                 VT.getSizeInBits() / 64);
9111   SmallVector<int, 8> LaneMask;
9112   LaneMask.resize(NumLanes * 2, -1);
9113   for (int i = 0; i < NumLanes; ++i)
9114     if (Lanes[i] >= 0) {
9115       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9116       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9117     }
9118
9119   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9120   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9121   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9122
9123   // Cast it back to the type we actually want.
9124   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9125
9126   // Now do a simple shuffle that isn't lane crossing.
9127   SmallVector<int, 8> NewMask;
9128   NewMask.resize(Size, -1);
9129   for (int i = 0; i < Size; ++i)
9130     if (Mask[i] >= 0)
9131       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9132   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9133          "Must not introduce lane crosses at this point!");
9134
9135   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9136 }
9137
9138 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9139 /// given mask.
9140 ///
9141 /// This returns true if the elements from a particular input are already in the
9142 /// slot required by the given mask and require no permutation.
9143 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9144   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9145   int Size = Mask.size();
9146   for (int i = 0; i < Size; ++i)
9147     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9148       return false;
9149
9150   return true;
9151 }
9152
9153 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9154 ///
9155 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9156 /// isn't available.
9157 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9158                                        const X86Subtarget *Subtarget,
9159                                        SelectionDAG &DAG) {
9160   SDLoc DL(Op);
9161   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9162   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9163   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9164   ArrayRef<int> Mask = SVOp->getMask();
9165   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9166
9167   SmallVector<int, 4> WidenedMask;
9168   if (canWidenShuffleElements(Mask, WidenedMask))
9169     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9170                                     DAG);
9171
9172   if (isSingleInputShuffleMask(Mask)) {
9173     // Check for being able to broadcast a single element.
9174     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9175                                                           Mask, Subtarget, DAG))
9176       return Broadcast;
9177
9178     // Use low duplicate instructions for masks that match their pattern.
9179     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9180       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9181
9182     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9183       // Non-half-crossing single input shuffles can be lowerid with an
9184       // interleaved permutation.
9185       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9186                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9187       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9188                          DAG.getConstant(VPERMILPMask, MVT::i8));
9189     }
9190
9191     // With AVX2 we have direct support for this permutation.
9192     if (Subtarget->hasAVX2())
9193       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9194                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9195
9196     // Otherwise, fall back.
9197     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9198                                                    DAG);
9199   }
9200
9201   // X86 has dedicated unpack instructions that can handle specific blend
9202   // operations: UNPCKH and UNPCKL.
9203   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9204     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9205   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9206     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9207   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9208     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9209   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9210     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9211
9212   // If we have a single input to the zero element, insert that into V1 if we
9213   // can do so cheaply.
9214   int NumV2Elements =
9215       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9216   if (NumV2Elements == 1 && Mask[0] >= 4)
9217     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9218             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9219       return Insertion;
9220
9221   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9222                                                 Subtarget, DAG))
9223     return Blend;
9224
9225   // Check if the blend happens to exactly fit that of SHUFPD.
9226   if ((Mask[0] == -1 || Mask[0] < 2) &&
9227       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9228       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9229       (Mask[3] == -1 || Mask[3] >= 6)) {
9230     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9231                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9232     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9233                        DAG.getConstant(SHUFPDMask, MVT::i8));
9234   }
9235   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9236       (Mask[1] == -1 || Mask[1] < 2) &&
9237       (Mask[2] == -1 || Mask[2] >= 6) &&
9238       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9239     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9240                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9241     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9242                        DAG.getConstant(SHUFPDMask, MVT::i8));
9243   }
9244
9245   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9246   // shuffle. However, if we have AVX2 and either inputs are already in place,
9247   // we will be able to shuffle even across lanes the other input in a single
9248   // instruction so skip this pattern.
9249   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9250                                  isShuffleMaskInputInPlace(1, Mask))))
9251     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9252             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9253       return Result;
9254
9255   // If we have AVX2 then we always want to lower with a blend because an v4 we
9256   // can fully permute the elements.
9257   if (Subtarget->hasAVX2())
9258     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9259                                                       Mask, DAG);
9260
9261   // Otherwise fall back on generic lowering.
9262   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9263 }
9264
9265 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9266 ///
9267 /// This routine is only called when we have AVX2 and thus a reasonable
9268 /// instruction set for v4i64 shuffling..
9269 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9270                                        const X86Subtarget *Subtarget,
9271                                        SelectionDAG &DAG) {
9272   SDLoc DL(Op);
9273   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9274   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9275   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9276   ArrayRef<int> Mask = SVOp->getMask();
9277   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9278   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9279
9280   SmallVector<int, 4> WidenedMask;
9281   if (canWidenShuffleElements(Mask, WidenedMask))
9282     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9283                                     DAG);
9284
9285   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9286                                                 Subtarget, DAG))
9287     return Blend;
9288
9289   // Check for being able to broadcast a single element.
9290   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9291                                                         Mask, Subtarget, DAG))
9292     return Broadcast;
9293
9294   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9295   // use lower latency instructions that will operate on both 128-bit lanes.
9296   SmallVector<int, 2> RepeatedMask;
9297   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9298     if (isSingleInputShuffleMask(Mask)) {
9299       int PSHUFDMask[] = {-1, -1, -1, -1};
9300       for (int i = 0; i < 2; ++i)
9301         if (RepeatedMask[i] >= 0) {
9302           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9303           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9304         }
9305       return DAG.getNode(
9306           ISD::BITCAST, DL, MVT::v4i64,
9307           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9308                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9309                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9310     }
9311   }
9312
9313   // AVX2 provides a direct instruction for permuting a single input across
9314   // lanes.
9315   if (isSingleInputShuffleMask(Mask))
9316     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9317                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9318
9319   // Try to use shift instructions.
9320   if (SDValue Shift =
9321           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9322     return Shift;
9323
9324   // Use dedicated unpack instructions for masks that match their pattern.
9325   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9326     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9327   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9328     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9329   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9330     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9331   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9332     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9333
9334   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9335   // shuffle. However, if we have AVX2 and either inputs are already in place,
9336   // we will be able to shuffle even across lanes the other input in a single
9337   // instruction so skip this pattern.
9338   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9339                                  isShuffleMaskInputInPlace(1, Mask))))
9340     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9341             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9342       return Result;
9343
9344   // Otherwise fall back on generic blend lowering.
9345   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9346                                                     Mask, DAG);
9347 }
9348
9349 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9350 ///
9351 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9352 /// isn't available.
9353 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9354                                        const X86Subtarget *Subtarget,
9355                                        SelectionDAG &DAG) {
9356   SDLoc DL(Op);
9357   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9358   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9359   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9360   ArrayRef<int> Mask = SVOp->getMask();
9361   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9362
9363   // If we have a single input to the zero element, insert that into V1 if we
9364   // can do so cheaply.
9365   int NumV2Elements =
9366       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 8; });
9367   if (NumV2Elements == 1 && Mask[0] >= 8)
9368     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9369             DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9370       return Insertion;
9371
9372   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9373                                                 Subtarget, DAG))
9374     return Blend;
9375
9376   // Check for being able to broadcast a single element.
9377   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9378                                                         Mask, Subtarget, DAG))
9379     return Broadcast;
9380
9381   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9382   // options to efficiently lower the shuffle.
9383   SmallVector<int, 4> RepeatedMask;
9384   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9385     assert(RepeatedMask.size() == 4 &&
9386            "Repeated masks must be half the mask width!");
9387
9388     // Use even/odd duplicate instructions for masks that match their pattern.
9389     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9390       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9391     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9392       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9393
9394     if (isSingleInputShuffleMask(Mask))
9395       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9396                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9397
9398     // Use dedicated unpack instructions for masks that match their pattern.
9399     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9400       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9401     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9402       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9403     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9404       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9405     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9406       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9407
9408     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9409     // have already handled any direct blends. We also need to squash the
9410     // repeated mask into a simulated v4f32 mask.
9411     for (int i = 0; i < 4; ++i)
9412       if (RepeatedMask[i] >= 8)
9413         RepeatedMask[i] -= 4;
9414     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9415   }
9416
9417   // If we have a single input shuffle with different shuffle patterns in the
9418   // two 128-bit lanes use the variable mask to VPERMILPS.
9419   if (isSingleInputShuffleMask(Mask)) {
9420     SDValue VPermMask[8];
9421     for (int i = 0; i < 8; ++i)
9422       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9423                                  : DAG.getConstant(Mask[i], MVT::i32);
9424     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9425       return DAG.getNode(
9426           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9427           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9428
9429     if (Subtarget->hasAVX2())
9430       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9431                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9432                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9433                                                  MVT::v8i32, VPermMask)),
9434                          V1);
9435
9436     // Otherwise, fall back.
9437     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9438                                                    DAG);
9439   }
9440
9441   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9442   // shuffle.
9443   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9444           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9445     return Result;
9446
9447   // If we have AVX2 then we always want to lower with a blend because at v8 we
9448   // can fully permute the elements.
9449   if (Subtarget->hasAVX2())
9450     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9451                                                       Mask, DAG);
9452
9453   // Otherwise fall back on generic lowering.
9454   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9455 }
9456
9457 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9458 ///
9459 /// This routine is only called when we have AVX2 and thus a reasonable
9460 /// instruction set for v8i32 shuffling..
9461 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9462                                        const X86Subtarget *Subtarget,
9463                                        SelectionDAG &DAG) {
9464   SDLoc DL(Op);
9465   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9466   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9467   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9468   ArrayRef<int> Mask = SVOp->getMask();
9469   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9470   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9471
9472   // Whenever we can lower this as a zext, that instruction is strictly faster
9473   // than any alternative. It also allows us to fold memory operands into the
9474   // shuffle in many cases.
9475   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9476                                                          Mask, Subtarget, DAG))
9477     return ZExt;
9478
9479   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9480                                                 Subtarget, DAG))
9481     return Blend;
9482
9483   // Check for being able to broadcast a single element.
9484   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9485                                                         Mask, Subtarget, DAG))
9486     return Broadcast;
9487
9488   // If the shuffle mask is repeated in each 128-bit lane we can use more
9489   // efficient instructions that mirror the shuffles across the two 128-bit
9490   // lanes.
9491   SmallVector<int, 4> RepeatedMask;
9492   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9493     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9494     if (isSingleInputShuffleMask(Mask))
9495       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9496                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9497
9498     // Use dedicated unpack instructions for masks that match their pattern.
9499     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9500       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9501     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9502       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9503     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9504       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9505     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9506       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9507   }
9508
9509   // Try to use shift instructions.
9510   if (SDValue Shift =
9511           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9512     return Shift;
9513
9514   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9515           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9516     return Rotate;
9517
9518   // If the shuffle patterns aren't repeated but it is a single input, directly
9519   // generate a cross-lane VPERMD instruction.
9520   if (isSingleInputShuffleMask(Mask)) {
9521     SDValue VPermMask[8];
9522     for (int i = 0; i < 8; ++i)
9523       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9524                                  : DAG.getConstant(Mask[i], MVT::i32);
9525     return DAG.getNode(
9526         X86ISD::VPERMV, DL, MVT::v8i32,
9527         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9528   }
9529
9530   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9531   // shuffle.
9532   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9533           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9534     return Result;
9535
9536   // Otherwise fall back on generic blend lowering.
9537   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9538                                                     Mask, DAG);
9539 }
9540
9541 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9542 ///
9543 /// This routine is only called when we have AVX2 and thus a reasonable
9544 /// instruction set for v16i16 shuffling..
9545 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9546                                         const X86Subtarget *Subtarget,
9547                                         SelectionDAG &DAG) {
9548   SDLoc DL(Op);
9549   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9550   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9551   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9552   ArrayRef<int> Mask = SVOp->getMask();
9553   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9554   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9555
9556   // Whenever we can lower this as a zext, that instruction is strictly faster
9557   // than any alternative. It also allows us to fold memory operands into the
9558   // shuffle in many cases.
9559   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9560                                                          Mask, Subtarget, DAG))
9561     return ZExt;
9562
9563   // Check for being able to broadcast a single element.
9564   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9565                                                         Mask, Subtarget, DAG))
9566     return Broadcast;
9567
9568   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9569                                                 Subtarget, DAG))
9570     return Blend;
9571
9572   // Use dedicated unpack instructions for masks that match their pattern.
9573   if (isShuffleEquivalent(V1, V2, Mask,
9574                           {// First 128-bit lane:
9575                            0, 16, 1, 17, 2, 18, 3, 19,
9576                            // Second 128-bit lane:
9577                            8, 24, 9, 25, 10, 26, 11, 27}))
9578     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9579   if (isShuffleEquivalent(V1, V2, Mask,
9580                           {// First 128-bit lane:
9581                            4, 20, 5, 21, 6, 22, 7, 23,
9582                            // Second 128-bit lane:
9583                            12, 28, 13, 29, 14, 30, 15, 31}))
9584     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9585
9586   // Try to use shift instructions.
9587   if (SDValue Shift =
9588           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9589     return Shift;
9590
9591   // Try to use byte rotation instructions.
9592   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9593           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9594     return Rotate;
9595
9596   if (isSingleInputShuffleMask(Mask)) {
9597     // There are no generalized cross-lane shuffle operations available on i16
9598     // element types.
9599     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9600       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9601                                                      Mask, DAG);
9602
9603     SmallVector<int, 8> RepeatedMask;
9604     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9605       // As this is a single-input shuffle, the repeated mask should be
9606       // a strictly valid v8i16 mask that we can pass through to the v8i16
9607       // lowering to handle even the v16 case.
9608       return lowerV8I16GeneralSingleInputVectorShuffle(
9609           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9610     }
9611
9612     SDValue PSHUFBMask[32];
9613     for (int i = 0; i < 16; ++i) {
9614       if (Mask[i] == -1) {
9615         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9616         continue;
9617       }
9618
9619       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9620       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9621       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9622       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9623     }
9624     return DAG.getNode(
9625         ISD::BITCAST, DL, MVT::v16i16,
9626         DAG.getNode(
9627             X86ISD::PSHUFB, DL, MVT::v32i8,
9628             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9629             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9630   }
9631
9632   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9633   // shuffle.
9634   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9635           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9636     return Result;
9637
9638   // Otherwise fall back on generic lowering.
9639   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9640 }
9641
9642 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9643 ///
9644 /// This routine is only called when we have AVX2 and thus a reasonable
9645 /// instruction set for v32i8 shuffling..
9646 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9647                                        const X86Subtarget *Subtarget,
9648                                        SelectionDAG &DAG) {
9649   SDLoc DL(Op);
9650   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9651   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9652   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9653   ArrayRef<int> Mask = SVOp->getMask();
9654   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9655   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9656
9657   // Whenever we can lower this as a zext, that instruction is strictly faster
9658   // than any alternative. It also allows us to fold memory operands into the
9659   // shuffle in many cases.
9660   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9661                                                          Mask, Subtarget, DAG))
9662     return ZExt;
9663
9664   // Check for being able to broadcast a single element.
9665   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9666                                                         Mask, Subtarget, DAG))
9667     return Broadcast;
9668
9669   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9670                                                 Subtarget, DAG))
9671     return Blend;
9672
9673   // Use dedicated unpack instructions for masks that match their pattern.
9674   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9675   // 256-bit lanes.
9676   if (isShuffleEquivalent(
9677           V1, V2, Mask,
9678           {// First 128-bit lane:
9679            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9680            // Second 128-bit lane:
9681            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9682     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9683   if (isShuffleEquivalent(
9684           V1, V2, Mask,
9685           {// First 128-bit lane:
9686            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9687            // Second 128-bit lane:
9688            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9689     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9690
9691   // Try to use shift instructions.
9692   if (SDValue Shift =
9693           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9694     return Shift;
9695
9696   // Try to use byte rotation instructions.
9697   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9698           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9699     return Rotate;
9700
9701   if (isSingleInputShuffleMask(Mask)) {
9702     // There are no generalized cross-lane shuffle operations available on i8
9703     // element types.
9704     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9705       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9706                                                      Mask, DAG);
9707
9708     SDValue PSHUFBMask[32];
9709     for (int i = 0; i < 32; ++i)
9710       PSHUFBMask[i] =
9711           Mask[i] < 0
9712               ? DAG.getUNDEF(MVT::i8)
9713               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9714
9715     return DAG.getNode(
9716         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9717         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9718   }
9719
9720   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9721   // shuffle.
9722   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9723           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9724     return Result;
9725
9726   // Otherwise fall back on generic lowering.
9727   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9728 }
9729
9730 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9731 ///
9732 /// This routine either breaks down the specific type of a 256-bit x86 vector
9733 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9734 /// together based on the available instructions.
9735 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9736                                         MVT VT, const X86Subtarget *Subtarget,
9737                                         SelectionDAG &DAG) {
9738   SDLoc DL(Op);
9739   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9740   ArrayRef<int> Mask = SVOp->getMask();
9741
9742   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9743   // check for those subtargets here and avoid much of the subtarget querying in
9744   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9745   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9746   // floating point types there eventually, just immediately cast everything to
9747   // a float and operate entirely in that domain.
9748   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9749     int ElementBits = VT.getScalarSizeInBits();
9750     if (ElementBits < 32)
9751       // No floating point type available, decompose into 128-bit vectors.
9752       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9753
9754     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9755                                 VT.getVectorNumElements());
9756     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9757     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9758     return DAG.getNode(ISD::BITCAST, DL, VT,
9759                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9760   }
9761
9762   switch (VT.SimpleTy) {
9763   case MVT::v4f64:
9764     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9765   case MVT::v4i64:
9766     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9767   case MVT::v8f32:
9768     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9769   case MVT::v8i32:
9770     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9771   case MVT::v16i16:
9772     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9773   case MVT::v32i8:
9774     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9775
9776   default:
9777     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9778   }
9779 }
9780
9781 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9782 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9783                                        const X86Subtarget *Subtarget,
9784                                        SelectionDAG &DAG) {
9785   SDLoc DL(Op);
9786   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9787   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9788   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9789   ArrayRef<int> Mask = SVOp->getMask();
9790   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9791
9792   // X86 has dedicated unpack instructions that can handle specific blend
9793   // operations: UNPCKH and UNPCKL.
9794   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9795     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9796   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9797     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9798
9799   // FIXME: Implement direct support for this type!
9800   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9801 }
9802
9803 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9804 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9805                                        const X86Subtarget *Subtarget,
9806                                        SelectionDAG &DAG) {
9807   SDLoc DL(Op);
9808   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9809   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9810   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9811   ArrayRef<int> Mask = SVOp->getMask();
9812   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9813
9814   // Use dedicated unpack instructions for masks that match their pattern.
9815   if (isShuffleEquivalent(V1, V2, Mask,
9816                           {// First 128-bit lane.
9817                            0, 16, 1, 17, 4, 20, 5, 21,
9818                            // Second 128-bit lane.
9819                            8, 24, 9, 25, 12, 28, 13, 29}))
9820     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9821   if (isShuffleEquivalent(V1, V2, Mask,
9822                           {// First 128-bit lane.
9823                            2, 18, 3, 19, 6, 22, 7, 23,
9824                            // Second 128-bit lane.
9825                            10, 26, 11, 27, 14, 30, 15, 31}))
9826     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9827
9828   // FIXME: Implement direct support for this type!
9829   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9830 }
9831
9832 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9833 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9834                                        const X86Subtarget *Subtarget,
9835                                        SelectionDAG &DAG) {
9836   SDLoc DL(Op);
9837   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9838   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9839   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9840   ArrayRef<int> Mask = SVOp->getMask();
9841   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9842
9843   // X86 has dedicated unpack instructions that can handle specific blend
9844   // operations: UNPCKH and UNPCKL.
9845   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9846     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9847   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9848     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9849
9850   // FIXME: Implement direct support for this type!
9851   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9852 }
9853
9854 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9855 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9856                                        const X86Subtarget *Subtarget,
9857                                        SelectionDAG &DAG) {
9858   SDLoc DL(Op);
9859   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9860   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9861   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9862   ArrayRef<int> Mask = SVOp->getMask();
9863   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9864
9865   // Use dedicated unpack instructions for masks that match their pattern.
9866   if (isShuffleEquivalent(V1, V2, Mask,
9867                           {// First 128-bit lane.
9868                            0, 16, 1, 17, 4, 20, 5, 21,
9869                            // Second 128-bit lane.
9870                            8, 24, 9, 25, 12, 28, 13, 29}))
9871     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9872   if (isShuffleEquivalent(V1, V2, Mask,
9873                           {// First 128-bit lane.
9874                            2, 18, 3, 19, 6, 22, 7, 23,
9875                            // Second 128-bit lane.
9876                            10, 26, 11, 27, 14, 30, 15, 31}))
9877     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9878
9879   // FIXME: Implement direct support for this type!
9880   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9881 }
9882
9883 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9884 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9885                                         const X86Subtarget *Subtarget,
9886                                         SelectionDAG &DAG) {
9887   SDLoc DL(Op);
9888   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9889   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9890   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9891   ArrayRef<int> Mask = SVOp->getMask();
9892   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9893   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9894
9895   // FIXME: Implement direct support for this type!
9896   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9897 }
9898
9899 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9900 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9901                                        const X86Subtarget *Subtarget,
9902                                        SelectionDAG &DAG) {
9903   SDLoc DL(Op);
9904   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9905   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9906   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9907   ArrayRef<int> Mask = SVOp->getMask();
9908   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9909   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9910
9911   // FIXME: Implement direct support for this type!
9912   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9913 }
9914
9915 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9916 ///
9917 /// This routine either breaks down the specific type of a 512-bit x86 vector
9918 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9919 /// together based on the available instructions.
9920 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9921                                         MVT VT, const X86Subtarget *Subtarget,
9922                                         SelectionDAG &DAG) {
9923   SDLoc DL(Op);
9924   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9925   ArrayRef<int> Mask = SVOp->getMask();
9926   assert(Subtarget->hasAVX512() &&
9927          "Cannot lower 512-bit vectors w/ basic ISA!");
9928
9929   // Check for being able to broadcast a single element.
9930   if (SDValue Broadcast =
9931           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
9932     return Broadcast;
9933
9934   // Dispatch to each element type for lowering. If we don't have supprot for
9935   // specific element type shuffles at 512 bits, immediately split them and
9936   // lower them. Each lowering routine of a given type is allowed to assume that
9937   // the requisite ISA extensions for that element type are available.
9938   switch (VT.SimpleTy) {
9939   case MVT::v8f64:
9940     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9941   case MVT::v16f32:
9942     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9943   case MVT::v8i64:
9944     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9945   case MVT::v16i32:
9946     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9947   case MVT::v32i16:
9948     if (Subtarget->hasBWI())
9949       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9950     break;
9951   case MVT::v64i8:
9952     if (Subtarget->hasBWI())
9953       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9954     break;
9955
9956   default:
9957     llvm_unreachable("Not a valid 512-bit x86 vector type!");
9958   }
9959
9960   // Otherwise fall back on splitting.
9961   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9962 }
9963
9964 /// \brief Top-level lowering for x86 vector shuffles.
9965 ///
9966 /// This handles decomposition, canonicalization, and lowering of all x86
9967 /// vector shuffles. Most of the specific lowering strategies are encapsulated
9968 /// above in helper routines. The canonicalization attempts to widen shuffles
9969 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
9970 /// s.t. only one of the two inputs needs to be tested, etc.
9971 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9972                                   SelectionDAG &DAG) {
9973   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9974   ArrayRef<int> Mask = SVOp->getMask();
9975   SDValue V1 = Op.getOperand(0);
9976   SDValue V2 = Op.getOperand(1);
9977   MVT VT = Op.getSimpleValueType();
9978   int NumElements = VT.getVectorNumElements();
9979   SDLoc dl(Op);
9980
9981   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9982
9983   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9984   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9985   if (V1IsUndef && V2IsUndef)
9986     return DAG.getUNDEF(VT);
9987
9988   // When we create a shuffle node we put the UNDEF node to second operand,
9989   // but in some cases the first operand may be transformed to UNDEF.
9990   // In this case we should just commute the node.
9991   if (V1IsUndef)
9992     return DAG.getCommutedVectorShuffle(*SVOp);
9993
9994   // Check for non-undef masks pointing at an undef vector and make the masks
9995   // undef as well. This makes it easier to match the shuffle based solely on
9996   // the mask.
9997   if (V2IsUndef)
9998     for (int M : Mask)
9999       if (M >= NumElements) {
10000         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10001         for (int &M : NewMask)
10002           if (M >= NumElements)
10003             M = -1;
10004         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10005       }
10006
10007   // We actually see shuffles that are entirely re-arrangements of a set of
10008   // zero inputs. This mostly happens while decomposing complex shuffles into
10009   // simple ones. Directly lower these as a buildvector of zeros.
10010   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10011   if (Zeroable.all())
10012     return getZeroVector(VT, Subtarget, DAG, dl);
10013
10014   // Try to collapse shuffles into using a vector type with fewer elements but
10015   // wider element types. We cap this to not form integers or floating point
10016   // elements wider than 64 bits, but it might be interesting to form i128
10017   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10018   SmallVector<int, 16> WidenedMask;
10019   if (VT.getScalarSizeInBits() < 64 &&
10020       canWidenShuffleElements(Mask, WidenedMask)) {
10021     MVT NewEltVT = VT.isFloatingPoint()
10022                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10023                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10024     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10025     // Make sure that the new vector type is legal. For example, v2f64 isn't
10026     // legal on SSE1.
10027     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10028       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10029       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10030       return DAG.getNode(ISD::BITCAST, dl, VT,
10031                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10032     }
10033   }
10034
10035   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10036   for (int M : SVOp->getMask())
10037     if (M < 0)
10038       ++NumUndefElements;
10039     else if (M < NumElements)
10040       ++NumV1Elements;
10041     else
10042       ++NumV2Elements;
10043
10044   // Commute the shuffle as needed such that more elements come from V1 than
10045   // V2. This allows us to match the shuffle pattern strictly on how many
10046   // elements come from V1 without handling the symmetric cases.
10047   if (NumV2Elements > NumV1Elements)
10048     return DAG.getCommutedVectorShuffle(*SVOp);
10049
10050   // When the number of V1 and V2 elements are the same, try to minimize the
10051   // number of uses of V2 in the low half of the vector. When that is tied,
10052   // ensure that the sum of indices for V1 is equal to or lower than the sum
10053   // indices for V2. When those are equal, try to ensure that the number of odd
10054   // indices for V1 is lower than the number of odd indices for V2.
10055   if (NumV1Elements == NumV2Elements) {
10056     int LowV1Elements = 0, LowV2Elements = 0;
10057     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10058       if (M >= NumElements)
10059         ++LowV2Elements;
10060       else if (M >= 0)
10061         ++LowV1Elements;
10062     if (LowV2Elements > LowV1Elements) {
10063       return DAG.getCommutedVectorShuffle(*SVOp);
10064     } else if (LowV2Elements == LowV1Elements) {
10065       int SumV1Indices = 0, SumV2Indices = 0;
10066       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10067         if (SVOp->getMask()[i] >= NumElements)
10068           SumV2Indices += i;
10069         else if (SVOp->getMask()[i] >= 0)
10070           SumV1Indices += i;
10071       if (SumV2Indices < SumV1Indices) {
10072         return DAG.getCommutedVectorShuffle(*SVOp);
10073       } else if (SumV2Indices == SumV1Indices) {
10074         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10075         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10076           if (SVOp->getMask()[i] >= NumElements)
10077             NumV2OddIndices += i % 2;
10078           else if (SVOp->getMask()[i] >= 0)
10079             NumV1OddIndices += i % 2;
10080         if (NumV2OddIndices < NumV1OddIndices)
10081           return DAG.getCommutedVectorShuffle(*SVOp);
10082       }
10083     }
10084   }
10085
10086   // For each vector width, delegate to a specialized lowering routine.
10087   if (VT.getSizeInBits() == 128)
10088     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10089
10090   if (VT.getSizeInBits() == 256)
10091     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10092
10093   // Force AVX-512 vectors to be scalarized for now.
10094   // FIXME: Implement AVX-512 support!
10095   if (VT.getSizeInBits() == 512)
10096     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10097
10098   llvm_unreachable("Unimplemented!");
10099 }
10100
10101 // This function assumes its argument is a BUILD_VECTOR of constants or
10102 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10103 // true.
10104 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10105                                     unsigned &MaskValue) {
10106   MaskValue = 0;
10107   unsigned NumElems = BuildVector->getNumOperands();
10108   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10109   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10110   unsigned NumElemsInLane = NumElems / NumLanes;
10111
10112   // Blend for v16i16 should be symetric for the both lanes.
10113   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10114     SDValue EltCond = BuildVector->getOperand(i);
10115     SDValue SndLaneEltCond =
10116         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10117
10118     int Lane1Cond = -1, Lane2Cond = -1;
10119     if (isa<ConstantSDNode>(EltCond))
10120       Lane1Cond = !isZero(EltCond);
10121     if (isa<ConstantSDNode>(SndLaneEltCond))
10122       Lane2Cond = !isZero(SndLaneEltCond);
10123
10124     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10125       // Lane1Cond != 0, means we want the first argument.
10126       // Lane1Cond == 0, means we want the second argument.
10127       // The encoding of this argument is 0 for the first argument, 1
10128       // for the second. Therefore, invert the condition.
10129       MaskValue |= !Lane1Cond << i;
10130     else if (Lane1Cond < 0)
10131       MaskValue |= !Lane2Cond << i;
10132     else
10133       return false;
10134   }
10135   return true;
10136 }
10137
10138 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10139 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10140                                            const X86Subtarget *Subtarget,
10141                                            SelectionDAG &DAG) {
10142   SDValue Cond = Op.getOperand(0);
10143   SDValue LHS = Op.getOperand(1);
10144   SDValue RHS = Op.getOperand(2);
10145   SDLoc dl(Op);
10146   MVT VT = Op.getSimpleValueType();
10147
10148   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10149     return SDValue();
10150   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10151
10152   // Only non-legal VSELECTs reach this lowering, convert those into generic
10153   // shuffles and re-use the shuffle lowering path for blends.
10154   SmallVector<int, 32> Mask;
10155   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10156     SDValue CondElt = CondBV->getOperand(i);
10157     Mask.push_back(
10158         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10159   }
10160   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10161 }
10162
10163 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10164   // A vselect where all conditions and data are constants can be optimized into
10165   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10166   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10167       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10168       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10169     return SDValue();
10170
10171   // Try to lower this to a blend-style vector shuffle. This can handle all
10172   // constant condition cases.
10173   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10174     return BlendOp;
10175
10176   // Variable blends are only legal from SSE4.1 onward.
10177   if (!Subtarget->hasSSE41())
10178     return SDValue();
10179
10180   // Only some types will be legal on some subtargets. If we can emit a legal
10181   // VSELECT-matching blend, return Op, and but if we need to expand, return
10182   // a null value.
10183   switch (Op.getSimpleValueType().SimpleTy) {
10184   default:
10185     // Most of the vector types have blends past SSE4.1.
10186     return Op;
10187
10188   case MVT::v32i8:
10189     // The byte blends for AVX vectors were introduced only in AVX2.
10190     if (Subtarget->hasAVX2())
10191       return Op;
10192
10193     return SDValue();
10194
10195   case MVT::v8i16:
10196   case MVT::v16i16:
10197     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10198     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10199       return Op;
10200
10201     // FIXME: We should custom lower this by fixing the condition and using i8
10202     // blends.
10203     return SDValue();
10204   }
10205 }
10206
10207 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10208   MVT VT = Op.getSimpleValueType();
10209   SDLoc dl(Op);
10210
10211   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10212     return SDValue();
10213
10214   if (VT.getSizeInBits() == 8) {
10215     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10216                                   Op.getOperand(0), Op.getOperand(1));
10217     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10218                                   DAG.getValueType(VT));
10219     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10220   }
10221
10222   if (VT.getSizeInBits() == 16) {
10223     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10224     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10225     if (Idx == 0)
10226       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10227                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10228                                      DAG.getNode(ISD::BITCAST, dl,
10229                                                  MVT::v4i32,
10230                                                  Op.getOperand(0)),
10231                                      Op.getOperand(1)));
10232     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10233                                   Op.getOperand(0), Op.getOperand(1));
10234     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10235                                   DAG.getValueType(VT));
10236     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10237   }
10238
10239   if (VT == MVT::f32) {
10240     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10241     // the result back to FR32 register. It's only worth matching if the
10242     // result has a single use which is a store or a bitcast to i32.  And in
10243     // the case of a store, it's not worth it if the index is a constant 0,
10244     // because a MOVSSmr can be used instead, which is smaller and faster.
10245     if (!Op.hasOneUse())
10246       return SDValue();
10247     SDNode *User = *Op.getNode()->use_begin();
10248     if ((User->getOpcode() != ISD::STORE ||
10249          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10250           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10251         (User->getOpcode() != ISD::BITCAST ||
10252          User->getValueType(0) != MVT::i32))
10253       return SDValue();
10254     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10255                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10256                                               Op.getOperand(0)),
10257                                               Op.getOperand(1));
10258     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10259   }
10260
10261   if (VT == MVT::i32 || VT == MVT::i64) {
10262     // ExtractPS/pextrq works with constant index.
10263     if (isa<ConstantSDNode>(Op.getOperand(1)))
10264       return Op;
10265   }
10266   return SDValue();
10267 }
10268
10269 /// Extract one bit from mask vector, like v16i1 or v8i1.
10270 /// AVX-512 feature.
10271 SDValue
10272 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10273   SDValue Vec = Op.getOperand(0);
10274   SDLoc dl(Vec);
10275   MVT VecVT = Vec.getSimpleValueType();
10276   SDValue Idx = Op.getOperand(1);
10277   MVT EltVT = Op.getSimpleValueType();
10278
10279   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10280   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10281          "Unexpected vector type in ExtractBitFromMaskVector");
10282
10283   // variable index can't be handled in mask registers,
10284   // extend vector to VR512
10285   if (!isa<ConstantSDNode>(Idx)) {
10286     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10287     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10288     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10289                               ExtVT.getVectorElementType(), Ext, Idx);
10290     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10291   }
10292
10293   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10294   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10295   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10296     rc = getRegClassFor(MVT::v16i1);
10297   unsigned MaxSift = rc->getSize()*8 - 1;
10298   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10299                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10300   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10301                     DAG.getConstant(MaxSift, MVT::i8));
10302   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10303                        DAG.getIntPtrConstant(0));
10304 }
10305
10306 SDValue
10307 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10308                                            SelectionDAG &DAG) const {
10309   SDLoc dl(Op);
10310   SDValue Vec = Op.getOperand(0);
10311   MVT VecVT = Vec.getSimpleValueType();
10312   SDValue Idx = Op.getOperand(1);
10313
10314   if (Op.getSimpleValueType() == MVT::i1)
10315     return ExtractBitFromMaskVector(Op, DAG);
10316
10317   if (!isa<ConstantSDNode>(Idx)) {
10318     if (VecVT.is512BitVector() ||
10319         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10320          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10321
10322       MVT MaskEltVT =
10323         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10324       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10325                                     MaskEltVT.getSizeInBits());
10326
10327       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10328       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10329                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10330                                 Idx, DAG.getConstant(0, getPointerTy()));
10331       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10332       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10333                         Perm, DAG.getConstant(0, getPointerTy()));
10334     }
10335     return SDValue();
10336   }
10337
10338   // If this is a 256-bit vector result, first extract the 128-bit vector and
10339   // then extract the element from the 128-bit vector.
10340   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10341
10342     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10343     // Get the 128-bit vector.
10344     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10345     MVT EltVT = VecVT.getVectorElementType();
10346
10347     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10348
10349     //if (IdxVal >= NumElems/2)
10350     //  IdxVal -= NumElems/2;
10351     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10352     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10353                        DAG.getConstant(IdxVal, MVT::i32));
10354   }
10355
10356   assert(VecVT.is128BitVector() && "Unexpected vector length");
10357
10358   if (Subtarget->hasSSE41()) {
10359     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10360     if (Res.getNode())
10361       return Res;
10362   }
10363
10364   MVT VT = Op.getSimpleValueType();
10365   // TODO: handle v16i8.
10366   if (VT.getSizeInBits() == 16) {
10367     SDValue Vec = Op.getOperand(0);
10368     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10369     if (Idx == 0)
10370       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10371                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10372                                      DAG.getNode(ISD::BITCAST, dl,
10373                                                  MVT::v4i32, Vec),
10374                                      Op.getOperand(1)));
10375     // Transform it so it match pextrw which produces a 32-bit result.
10376     MVT EltVT = MVT::i32;
10377     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10378                                   Op.getOperand(0), Op.getOperand(1));
10379     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10380                                   DAG.getValueType(VT));
10381     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10382   }
10383
10384   if (VT.getSizeInBits() == 32) {
10385     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10386     if (Idx == 0)
10387       return Op;
10388
10389     // SHUFPS the element to the lowest double word, then movss.
10390     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10391     MVT VVT = Op.getOperand(0).getSimpleValueType();
10392     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10393                                        DAG.getUNDEF(VVT), Mask);
10394     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10395                        DAG.getIntPtrConstant(0));
10396   }
10397
10398   if (VT.getSizeInBits() == 64) {
10399     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10400     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10401     //        to match extract_elt for f64.
10402     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10403     if (Idx == 0)
10404       return Op;
10405
10406     // UNPCKHPD the element to the lowest double word, then movsd.
10407     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10408     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10409     int Mask[2] = { 1, -1 };
10410     MVT VVT = Op.getOperand(0).getSimpleValueType();
10411     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10412                                        DAG.getUNDEF(VVT), Mask);
10413     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10414                        DAG.getIntPtrConstant(0));
10415   }
10416
10417   return SDValue();
10418 }
10419
10420 /// Insert one bit to mask vector, like v16i1 or v8i1.
10421 /// AVX-512 feature.
10422 SDValue
10423 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10424   SDLoc dl(Op);
10425   SDValue Vec = Op.getOperand(0);
10426   SDValue Elt = Op.getOperand(1);
10427   SDValue Idx = Op.getOperand(2);
10428   MVT VecVT = Vec.getSimpleValueType();
10429
10430   if (!isa<ConstantSDNode>(Idx)) {
10431     // Non constant index. Extend source and destination,
10432     // insert element and then truncate the result.
10433     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10434     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10435     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10436       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10437       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10438     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10439   }
10440
10441   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10442   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10443   if (Vec.getOpcode() == ISD::UNDEF)
10444     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10445                        DAG.getConstant(IdxVal, MVT::i8));
10446   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10447   unsigned MaxSift = rc->getSize()*8 - 1;
10448   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10449                     DAG.getConstant(MaxSift, MVT::i8));
10450   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10451                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10452   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10453 }
10454
10455 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10456                                                   SelectionDAG &DAG) const {
10457   MVT VT = Op.getSimpleValueType();
10458   MVT EltVT = VT.getVectorElementType();
10459
10460   if (EltVT == MVT::i1)
10461     return InsertBitToMaskVector(Op, DAG);
10462
10463   SDLoc dl(Op);
10464   SDValue N0 = Op.getOperand(0);
10465   SDValue N1 = Op.getOperand(1);
10466   SDValue N2 = Op.getOperand(2);
10467   if (!isa<ConstantSDNode>(N2))
10468     return SDValue();
10469   auto *N2C = cast<ConstantSDNode>(N2);
10470   unsigned IdxVal = N2C->getZExtValue();
10471
10472   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10473   // into that, and then insert the subvector back into the result.
10474   if (VT.is256BitVector() || VT.is512BitVector()) {
10475     // Get the desired 128-bit vector half.
10476     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10477
10478     // Insert the element into the desired half.
10479     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10480     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10481
10482     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10483                     DAG.getConstant(IdxIn128, MVT::i32));
10484
10485     // Insert the changed part back to the 256-bit vector
10486     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10487   }
10488   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10489
10490   if (Subtarget->hasSSE41()) {
10491     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10492       unsigned Opc;
10493       if (VT == MVT::v8i16) {
10494         Opc = X86ISD::PINSRW;
10495       } else {
10496         assert(VT == MVT::v16i8);
10497         Opc = X86ISD::PINSRB;
10498       }
10499
10500       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10501       // argument.
10502       if (N1.getValueType() != MVT::i32)
10503         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10504       if (N2.getValueType() != MVT::i32)
10505         N2 = DAG.getIntPtrConstant(IdxVal);
10506       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10507     }
10508
10509     if (EltVT == MVT::f32) {
10510       // Bits [7:6] of the constant are the source select.  This will always be
10511       //  zero here.  The DAG Combiner may combine an extract_elt index into
10512       //  these
10513       //  bits.  For example (insert (extract, 3), 2) could be matched by
10514       //  putting
10515       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10516       // Bits [5:4] of the constant are the destination select.  This is the
10517       //  value of the incoming immediate.
10518       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10519       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10520       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10521       // Create this as a scalar to vector..
10522       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10523       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10524     }
10525
10526     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10527       // PINSR* works with constant index.
10528       return Op;
10529     }
10530   }
10531
10532   if (EltVT == MVT::i8)
10533     return SDValue();
10534
10535   if (EltVT.getSizeInBits() == 16) {
10536     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10537     // as its second argument.
10538     if (N1.getValueType() != MVT::i32)
10539       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10540     if (N2.getValueType() != MVT::i32)
10541       N2 = DAG.getIntPtrConstant(IdxVal);
10542     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10543   }
10544   return SDValue();
10545 }
10546
10547 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10548   SDLoc dl(Op);
10549   MVT OpVT = Op.getSimpleValueType();
10550
10551   // If this is a 256-bit vector result, first insert into a 128-bit
10552   // vector and then insert into the 256-bit vector.
10553   if (!OpVT.is128BitVector()) {
10554     // Insert into a 128-bit vector.
10555     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10556     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10557                                  OpVT.getVectorNumElements() / SizeFactor);
10558
10559     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10560
10561     // Insert the 128-bit vector.
10562     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10563   }
10564
10565   if (OpVT == MVT::v1i64 &&
10566       Op.getOperand(0).getValueType() == MVT::i64)
10567     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10568
10569   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10570   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10571   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10572                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10573 }
10574
10575 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10576 // a simple subregister reference or explicit instructions to grab
10577 // upper bits of a vector.
10578 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10579                                       SelectionDAG &DAG) {
10580   SDLoc dl(Op);
10581   SDValue In =  Op.getOperand(0);
10582   SDValue Idx = Op.getOperand(1);
10583   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10584   MVT ResVT   = Op.getSimpleValueType();
10585   MVT InVT    = In.getSimpleValueType();
10586
10587   if (Subtarget->hasFp256()) {
10588     if (ResVT.is128BitVector() &&
10589         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10590         isa<ConstantSDNode>(Idx)) {
10591       return Extract128BitVector(In, IdxVal, DAG, dl);
10592     }
10593     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10594         isa<ConstantSDNode>(Idx)) {
10595       return Extract256BitVector(In, IdxVal, DAG, dl);
10596     }
10597   }
10598   return SDValue();
10599 }
10600
10601 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10602 // simple superregister reference or explicit instructions to insert
10603 // the upper bits of a vector.
10604 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10605                                      SelectionDAG &DAG) {
10606   if (!Subtarget->hasAVX())
10607     return SDValue();
10608
10609   SDLoc dl(Op);
10610   SDValue Vec = Op.getOperand(0);
10611   SDValue SubVec = Op.getOperand(1);
10612   SDValue Idx = Op.getOperand(2);
10613
10614   if (!isa<ConstantSDNode>(Idx))
10615     return SDValue();
10616
10617   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10618   MVT OpVT = Op.getSimpleValueType();
10619   MVT SubVecVT = SubVec.getSimpleValueType();
10620
10621   // Fold two 16-byte subvector loads into one 32-byte load:
10622   // (insert_subvector (insert_subvector undef, (load addr), 0),
10623   //                   (load addr + 16), Elts/2)
10624   // --> load32 addr
10625   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10626       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10627       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10628       !Subtarget->isUnalignedMem32Slow()) {
10629     SDValue SubVec2 = Vec.getOperand(1);
10630     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10631       if (Idx2->getZExtValue() == 0) {
10632         SDValue Ops[] = { SubVec2, SubVec };
10633         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10634         if (LD.getNode())
10635           return LD;
10636       }
10637     }
10638   }
10639
10640   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10641       SubVecVT.is128BitVector())
10642     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10643
10644   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10645     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10646
10647   if (OpVT.getVectorElementType() == MVT::i1) {
10648     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10649       return Op;
10650     SDValue ZeroIdx = DAG.getIntPtrConstant(0);
10651     SDValue Undef = DAG.getUNDEF(OpVT);
10652     unsigned NumElems = OpVT.getVectorNumElements();
10653     SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
10654
10655     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10656       // Zero upper bits of the Vec
10657       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10658       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10659
10660       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10661                                  SubVec, ZeroIdx);
10662       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10663       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10664     }
10665     if (IdxVal == 0) {
10666       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10667                                  SubVec, ZeroIdx);
10668       // Zero upper bits of the Vec2
10669       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10670       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10671       // Zero lower bits of the Vec
10672       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10673       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10674       // Merge them together
10675       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10676     }
10677   }
10678   return SDValue();
10679 }
10680
10681 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10682 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10683 // one of the above mentioned nodes. It has to be wrapped because otherwise
10684 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10685 // be used to form addressing mode. These wrapped nodes will be selected
10686 // into MOV32ri.
10687 SDValue
10688 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10689   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10690
10691   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10692   // global base reg.
10693   unsigned char OpFlag = 0;
10694   unsigned WrapperKind = X86ISD::Wrapper;
10695   CodeModel::Model M = DAG.getTarget().getCodeModel();
10696
10697   if (Subtarget->isPICStyleRIPRel() &&
10698       (M == CodeModel::Small || M == CodeModel::Kernel))
10699     WrapperKind = X86ISD::WrapperRIP;
10700   else if (Subtarget->isPICStyleGOT())
10701     OpFlag = X86II::MO_GOTOFF;
10702   else if (Subtarget->isPICStyleStubPIC())
10703     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10704
10705   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10706                                              CP->getAlignment(),
10707                                              CP->getOffset(), OpFlag);
10708   SDLoc DL(CP);
10709   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10710   // With PIC, the address is actually $g + Offset.
10711   if (OpFlag) {
10712     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10713                          DAG.getNode(X86ISD::GlobalBaseReg,
10714                                      SDLoc(), getPointerTy()),
10715                          Result);
10716   }
10717
10718   return Result;
10719 }
10720
10721 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10722   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10723
10724   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10725   // global base reg.
10726   unsigned char OpFlag = 0;
10727   unsigned WrapperKind = X86ISD::Wrapper;
10728   CodeModel::Model M = DAG.getTarget().getCodeModel();
10729
10730   if (Subtarget->isPICStyleRIPRel() &&
10731       (M == CodeModel::Small || M == CodeModel::Kernel))
10732     WrapperKind = X86ISD::WrapperRIP;
10733   else if (Subtarget->isPICStyleGOT())
10734     OpFlag = X86II::MO_GOTOFF;
10735   else if (Subtarget->isPICStyleStubPIC())
10736     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10737
10738   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10739                                           OpFlag);
10740   SDLoc DL(JT);
10741   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10742
10743   // With PIC, the address is actually $g + Offset.
10744   if (OpFlag)
10745     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10746                          DAG.getNode(X86ISD::GlobalBaseReg,
10747                                      SDLoc(), getPointerTy()),
10748                          Result);
10749
10750   return Result;
10751 }
10752
10753 SDValue
10754 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10755   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10756
10757   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10758   // global base reg.
10759   unsigned char OpFlag = 0;
10760   unsigned WrapperKind = X86ISD::Wrapper;
10761   CodeModel::Model M = DAG.getTarget().getCodeModel();
10762
10763   if (Subtarget->isPICStyleRIPRel() &&
10764       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10765     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10766       OpFlag = X86II::MO_GOTPCREL;
10767     WrapperKind = X86ISD::WrapperRIP;
10768   } else if (Subtarget->isPICStyleGOT()) {
10769     OpFlag = X86II::MO_GOT;
10770   } else if (Subtarget->isPICStyleStubPIC()) {
10771     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10772   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10773     OpFlag = X86II::MO_DARWIN_NONLAZY;
10774   }
10775
10776   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10777
10778   SDLoc DL(Op);
10779   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10780
10781   // With PIC, the address is actually $g + Offset.
10782   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10783       !Subtarget->is64Bit()) {
10784     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10785                          DAG.getNode(X86ISD::GlobalBaseReg,
10786                                      SDLoc(), getPointerTy()),
10787                          Result);
10788   }
10789
10790   // For symbols that require a load from a stub to get the address, emit the
10791   // load.
10792   if (isGlobalStubReference(OpFlag))
10793     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10794                          MachinePointerInfo::getGOT(), false, false, false, 0);
10795
10796   return Result;
10797 }
10798
10799 SDValue
10800 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10801   // Create the TargetBlockAddressAddress node.
10802   unsigned char OpFlags =
10803     Subtarget->ClassifyBlockAddressReference();
10804   CodeModel::Model M = DAG.getTarget().getCodeModel();
10805   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10806   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10807   SDLoc dl(Op);
10808   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10809                                              OpFlags);
10810
10811   if (Subtarget->isPICStyleRIPRel() &&
10812       (M == CodeModel::Small || M == CodeModel::Kernel))
10813     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10814   else
10815     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10816
10817   // With PIC, the address is actually $g + Offset.
10818   if (isGlobalRelativeToPICBase(OpFlags)) {
10819     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10820                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10821                          Result);
10822   }
10823
10824   return Result;
10825 }
10826
10827 SDValue
10828 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10829                                       int64_t Offset, SelectionDAG &DAG) const {
10830   // Create the TargetGlobalAddress node, folding in the constant
10831   // offset if it is legal.
10832   unsigned char OpFlags =
10833       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10834   CodeModel::Model M = DAG.getTarget().getCodeModel();
10835   SDValue Result;
10836   if (OpFlags == X86II::MO_NO_FLAG &&
10837       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10838     // A direct static reference to a global.
10839     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10840     Offset = 0;
10841   } else {
10842     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10843   }
10844
10845   if (Subtarget->isPICStyleRIPRel() &&
10846       (M == CodeModel::Small || M == CodeModel::Kernel))
10847     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10848   else
10849     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10850
10851   // With PIC, the address is actually $g + Offset.
10852   if (isGlobalRelativeToPICBase(OpFlags)) {
10853     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10854                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10855                          Result);
10856   }
10857
10858   // For globals that require a load from a stub to get the address, emit the
10859   // load.
10860   if (isGlobalStubReference(OpFlags))
10861     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10862                          MachinePointerInfo::getGOT(), false, false, false, 0);
10863
10864   // If there was a non-zero offset that we didn't fold, create an explicit
10865   // addition for it.
10866   if (Offset != 0)
10867     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10868                          DAG.getConstant(Offset, getPointerTy()));
10869
10870   return Result;
10871 }
10872
10873 SDValue
10874 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10875   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10876   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10877   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10878 }
10879
10880 static SDValue
10881 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10882            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10883            unsigned char OperandFlags, bool LocalDynamic = false) {
10884   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10885   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10886   SDLoc dl(GA);
10887   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10888                                            GA->getValueType(0),
10889                                            GA->getOffset(),
10890                                            OperandFlags);
10891
10892   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10893                                            : X86ISD::TLSADDR;
10894
10895   if (InFlag) {
10896     SDValue Ops[] = { Chain,  TGA, *InFlag };
10897     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10898   } else {
10899     SDValue Ops[]  = { Chain, TGA };
10900     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10901   }
10902
10903   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10904   MFI->setAdjustsStack(true);
10905   MFI->setHasCalls(true);
10906
10907   SDValue Flag = Chain.getValue(1);
10908   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10909 }
10910
10911 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10912 static SDValue
10913 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10914                                 const EVT PtrVT) {
10915   SDValue InFlag;
10916   SDLoc dl(GA);  // ? function entry point might be better
10917   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10918                                    DAG.getNode(X86ISD::GlobalBaseReg,
10919                                                SDLoc(), PtrVT), InFlag);
10920   InFlag = Chain.getValue(1);
10921
10922   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10923 }
10924
10925 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10926 static SDValue
10927 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10928                                 const EVT PtrVT) {
10929   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10930                     X86::RAX, X86II::MO_TLSGD);
10931 }
10932
10933 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10934                                            SelectionDAG &DAG,
10935                                            const EVT PtrVT,
10936                                            bool is64Bit) {
10937   SDLoc dl(GA);
10938
10939   // Get the start address of the TLS block for this module.
10940   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10941       .getInfo<X86MachineFunctionInfo>();
10942   MFI->incNumLocalDynamicTLSAccesses();
10943
10944   SDValue Base;
10945   if (is64Bit) {
10946     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10947                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10948   } else {
10949     SDValue InFlag;
10950     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10951         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10952     InFlag = Chain.getValue(1);
10953     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10954                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10955   }
10956
10957   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10958   // of Base.
10959
10960   // Build x@dtpoff.
10961   unsigned char OperandFlags = X86II::MO_DTPOFF;
10962   unsigned WrapperKind = X86ISD::Wrapper;
10963   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10964                                            GA->getValueType(0),
10965                                            GA->getOffset(), OperandFlags);
10966   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10967
10968   // Add x@dtpoff with the base.
10969   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10970 }
10971
10972 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10973 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10974                                    const EVT PtrVT, TLSModel::Model model,
10975                                    bool is64Bit, bool isPIC) {
10976   SDLoc dl(GA);
10977
10978   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10979   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10980                                                          is64Bit ? 257 : 256));
10981
10982   SDValue ThreadPointer =
10983       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10984                   MachinePointerInfo(Ptr), false, false, false, 0);
10985
10986   unsigned char OperandFlags = 0;
10987   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10988   // initialexec.
10989   unsigned WrapperKind = X86ISD::Wrapper;
10990   if (model == TLSModel::LocalExec) {
10991     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10992   } else if (model == TLSModel::InitialExec) {
10993     if (is64Bit) {
10994       OperandFlags = X86II::MO_GOTTPOFF;
10995       WrapperKind = X86ISD::WrapperRIP;
10996     } else {
10997       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10998     }
10999   } else {
11000     llvm_unreachable("Unexpected model");
11001   }
11002
11003   // emit "addl x@ntpoff,%eax" (local exec)
11004   // or "addl x@indntpoff,%eax" (initial exec)
11005   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11006   SDValue TGA =
11007       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11008                                  GA->getOffset(), OperandFlags);
11009   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11010
11011   if (model == TLSModel::InitialExec) {
11012     if (isPIC && !is64Bit) {
11013       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11014                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11015                            Offset);
11016     }
11017
11018     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11019                          MachinePointerInfo::getGOT(), false, false, false, 0);
11020   }
11021
11022   // The address of the thread local variable is the add of the thread
11023   // pointer with the offset of the variable.
11024   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11025 }
11026
11027 SDValue
11028 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11029
11030   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11031   const GlobalValue *GV = GA->getGlobal();
11032
11033   if (Subtarget->isTargetELF()) {
11034     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11035
11036     switch (model) {
11037       case TLSModel::GeneralDynamic:
11038         if (Subtarget->is64Bit())
11039           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11040         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11041       case TLSModel::LocalDynamic:
11042         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11043                                            Subtarget->is64Bit());
11044       case TLSModel::InitialExec:
11045       case TLSModel::LocalExec:
11046         return LowerToTLSExecModel(
11047             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11048             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11049     }
11050     llvm_unreachable("Unknown TLS model.");
11051   }
11052
11053   if (Subtarget->isTargetDarwin()) {
11054     // Darwin only has one model of TLS.  Lower to that.
11055     unsigned char OpFlag = 0;
11056     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11057                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11058
11059     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11060     // global base reg.
11061     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11062                  !Subtarget->is64Bit();
11063     if (PIC32)
11064       OpFlag = X86II::MO_TLVP_PIC_BASE;
11065     else
11066       OpFlag = X86II::MO_TLVP;
11067     SDLoc DL(Op);
11068     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11069                                                 GA->getValueType(0),
11070                                                 GA->getOffset(), OpFlag);
11071     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11072
11073     // With PIC32, the address is actually $g + Offset.
11074     if (PIC32)
11075       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11076                            DAG.getNode(X86ISD::GlobalBaseReg,
11077                                        SDLoc(), getPointerTy()),
11078                            Offset);
11079
11080     // Lowering the machine isd will make sure everything is in the right
11081     // location.
11082     SDValue Chain = DAG.getEntryNode();
11083     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11084     SDValue Args[] = { Chain, Offset };
11085     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11086
11087     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11088     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11089     MFI->setAdjustsStack(true);
11090
11091     // And our return value (tls address) is in the standard call return value
11092     // location.
11093     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11094     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11095                               Chain.getValue(1));
11096   }
11097
11098   if (Subtarget->isTargetKnownWindowsMSVC() ||
11099       Subtarget->isTargetWindowsGNU()) {
11100     // Just use the implicit TLS architecture
11101     // Need to generate someting similar to:
11102     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11103     //                                  ; from TEB
11104     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11105     //   mov     rcx, qword [rdx+rcx*8]
11106     //   mov     eax, .tls$:tlsvar
11107     //   [rax+rcx] contains the address
11108     // Windows 64bit: gs:0x58
11109     // Windows 32bit: fs:__tls_array
11110
11111     SDLoc dl(GA);
11112     SDValue Chain = DAG.getEntryNode();
11113
11114     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11115     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11116     // use its literal value of 0x2C.
11117     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11118                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11119                                                              256)
11120                                         : Type::getInt32PtrTy(*DAG.getContext(),
11121                                                               257));
11122
11123     SDValue TlsArray =
11124         Subtarget->is64Bit()
11125             ? DAG.getIntPtrConstant(0x58)
11126             : (Subtarget->isTargetWindowsGNU()
11127                    ? DAG.getIntPtrConstant(0x2C)
11128                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11129
11130     SDValue ThreadPointer =
11131         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11132                     MachinePointerInfo(Ptr), false, false, false, 0);
11133
11134     // Load the _tls_index variable
11135     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11136     if (Subtarget->is64Bit())
11137       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11138                            IDX, MachinePointerInfo(), MVT::i32,
11139                            false, false, false, 0);
11140     else
11141       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11142                         false, false, false, 0);
11143
11144     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11145                                     getPointerTy());
11146     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11147
11148     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11149     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11150                       false, false, false, 0);
11151
11152     // Get the offset of start of .tls section
11153     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11154                                              GA->getValueType(0),
11155                                              GA->getOffset(), X86II::MO_SECREL);
11156     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11157
11158     // The address of the thread local variable is the add of the thread
11159     // pointer with the offset of the variable.
11160     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11161   }
11162
11163   llvm_unreachable("TLS not implemented for this target.");
11164 }
11165
11166 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11167 /// and take a 2 x i32 value to shift plus a shift amount.
11168 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11169   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11170   MVT VT = Op.getSimpleValueType();
11171   unsigned VTBits = VT.getSizeInBits();
11172   SDLoc dl(Op);
11173   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11174   SDValue ShOpLo = Op.getOperand(0);
11175   SDValue ShOpHi = Op.getOperand(1);
11176   SDValue ShAmt  = Op.getOperand(2);
11177   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11178   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11179   // during isel.
11180   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11181                                   DAG.getConstant(VTBits - 1, MVT::i8));
11182   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11183                                      DAG.getConstant(VTBits - 1, MVT::i8))
11184                        : DAG.getConstant(0, VT);
11185
11186   SDValue Tmp2, Tmp3;
11187   if (Op.getOpcode() == ISD::SHL_PARTS) {
11188     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11189     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11190   } else {
11191     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11192     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11193   }
11194
11195   // If the shift amount is larger or equal than the width of a part we can't
11196   // rely on the results of shld/shrd. Insert a test and select the appropriate
11197   // values for large shift amounts.
11198   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11199                                 DAG.getConstant(VTBits, MVT::i8));
11200   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11201                              AndNode, DAG.getConstant(0, MVT::i8));
11202
11203   SDValue Hi, Lo;
11204   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11205   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11206   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11207
11208   if (Op.getOpcode() == ISD::SHL_PARTS) {
11209     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11210     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11211   } else {
11212     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11213     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11214   }
11215
11216   SDValue Ops[2] = { Lo, Hi };
11217   return DAG.getMergeValues(Ops, dl);
11218 }
11219
11220 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11221                                            SelectionDAG &DAG) const {
11222   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11223   SDLoc dl(Op);
11224
11225   if (SrcVT.isVector()) {
11226     if (SrcVT.getVectorElementType() == MVT::i1) {
11227       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11228       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11229                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11230                                      Op.getOperand(0)));
11231     }
11232     return SDValue();
11233   }
11234
11235   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11236          "Unknown SINT_TO_FP to lower!");
11237
11238   // These are really Legal; return the operand so the caller accepts it as
11239   // Legal.
11240   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11241     return Op;
11242   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11243       Subtarget->is64Bit()) {
11244     return Op;
11245   }
11246
11247   unsigned Size = SrcVT.getSizeInBits()/8;
11248   MachineFunction &MF = DAG.getMachineFunction();
11249   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11250   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11251   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11252                                StackSlot,
11253                                MachinePointerInfo::getFixedStack(SSFI),
11254                                false, false, 0);
11255   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11256 }
11257
11258 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11259                                      SDValue StackSlot,
11260                                      SelectionDAG &DAG) const {
11261   // Build the FILD
11262   SDLoc DL(Op);
11263   SDVTList Tys;
11264   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11265   if (useSSE)
11266     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11267   else
11268     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11269
11270   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11271
11272   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11273   MachineMemOperand *MMO;
11274   if (FI) {
11275     int SSFI = FI->getIndex();
11276     MMO =
11277       DAG.getMachineFunction()
11278       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11279                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11280   } else {
11281     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11282     StackSlot = StackSlot.getOperand(1);
11283   }
11284   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11285   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11286                                            X86ISD::FILD, DL,
11287                                            Tys, Ops, SrcVT, MMO);
11288
11289   if (useSSE) {
11290     Chain = Result.getValue(1);
11291     SDValue InFlag = Result.getValue(2);
11292
11293     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11294     // shouldn't be necessary except that RFP cannot be live across
11295     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11296     MachineFunction &MF = DAG.getMachineFunction();
11297     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11298     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11299     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11300     Tys = DAG.getVTList(MVT::Other);
11301     SDValue Ops[] = {
11302       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11303     };
11304     MachineMemOperand *MMO =
11305       DAG.getMachineFunction()
11306       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11307                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11308
11309     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11310                                     Ops, Op.getValueType(), MMO);
11311     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11312                          MachinePointerInfo::getFixedStack(SSFI),
11313                          false, false, false, 0);
11314   }
11315
11316   return Result;
11317 }
11318
11319 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11320 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11321                                                SelectionDAG &DAG) const {
11322   // This algorithm is not obvious. Here it is what we're trying to output:
11323   /*
11324      movq       %rax,  %xmm0
11325      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11326      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11327      #ifdef __SSE3__
11328        haddpd   %xmm0, %xmm0
11329      #else
11330        pshufd   $0x4e, %xmm0, %xmm1
11331        addpd    %xmm1, %xmm0
11332      #endif
11333   */
11334
11335   SDLoc dl(Op);
11336   LLVMContext *Context = DAG.getContext();
11337
11338   // Build some magic constants.
11339   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11340   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11341   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11342
11343   SmallVector<Constant*,2> CV1;
11344   CV1.push_back(
11345     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11346                                       APInt(64, 0x4330000000000000ULL))));
11347   CV1.push_back(
11348     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11349                                       APInt(64, 0x4530000000000000ULL))));
11350   Constant *C1 = ConstantVector::get(CV1);
11351   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11352
11353   // Load the 64-bit value into an XMM register.
11354   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11355                             Op.getOperand(0));
11356   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11357                               MachinePointerInfo::getConstantPool(),
11358                               false, false, false, 16);
11359   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11360                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11361                               CLod0);
11362
11363   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11364                               MachinePointerInfo::getConstantPool(),
11365                               false, false, false, 16);
11366   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11367   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11368   SDValue Result;
11369
11370   if (Subtarget->hasSSE3()) {
11371     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11372     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11373   } else {
11374     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11375     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11376                                            S2F, 0x4E, DAG);
11377     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11378                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11379                          Sub);
11380   }
11381
11382   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11383                      DAG.getIntPtrConstant(0));
11384 }
11385
11386 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11387 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11388                                                SelectionDAG &DAG) const {
11389   SDLoc dl(Op);
11390   // FP constant to bias correct the final result.
11391   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11392                                    MVT::f64);
11393
11394   // Load the 32-bit value into an XMM register.
11395   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11396                              Op.getOperand(0));
11397
11398   // Zero out the upper parts of the register.
11399   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11400
11401   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11402                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11403                      DAG.getIntPtrConstant(0));
11404
11405   // Or the load with the bias.
11406   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11407                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11408                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11409                                                    MVT::v2f64, Load)),
11410                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11411                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11412                                                    MVT::v2f64, Bias)));
11413   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11414                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11415                    DAG.getIntPtrConstant(0));
11416
11417   // Subtract the bias.
11418   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11419
11420   // Handle final rounding.
11421   EVT DestVT = Op.getValueType();
11422
11423   if (DestVT.bitsLT(MVT::f64))
11424     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11425                        DAG.getIntPtrConstant(0));
11426   if (DestVT.bitsGT(MVT::f64))
11427     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11428
11429   // Handle final rounding.
11430   return Sub;
11431 }
11432
11433 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11434                                      const X86Subtarget &Subtarget) {
11435   // The algorithm is the following:
11436   // #ifdef __SSE4_1__
11437   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11438   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11439   //                                 (uint4) 0x53000000, 0xaa);
11440   // #else
11441   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11442   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11443   // #endif
11444   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11445   //     return (float4) lo + fhi;
11446
11447   SDLoc DL(Op);
11448   SDValue V = Op->getOperand(0);
11449   EVT VecIntVT = V.getValueType();
11450   bool Is128 = VecIntVT == MVT::v4i32;
11451   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11452   // If we convert to something else than the supported type, e.g., to v4f64,
11453   // abort early.
11454   if (VecFloatVT != Op->getValueType(0))
11455     return SDValue();
11456
11457   unsigned NumElts = VecIntVT.getVectorNumElements();
11458   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11459          "Unsupported custom type");
11460   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11461
11462   // In the #idef/#else code, we have in common:
11463   // - The vector of constants:
11464   // -- 0x4b000000
11465   // -- 0x53000000
11466   // - A shift:
11467   // -- v >> 16
11468
11469   // Create the splat vector for 0x4b000000.
11470   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11471   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11472                            CstLow, CstLow, CstLow, CstLow};
11473   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11474                                   makeArrayRef(&CstLowArray[0], NumElts));
11475   // Create the splat vector for 0x53000000.
11476   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11477   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11478                             CstHigh, CstHigh, CstHigh, CstHigh};
11479   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11480                                    makeArrayRef(&CstHighArray[0], NumElts));
11481
11482   // Create the right shift.
11483   SDValue CstShift = DAG.getConstant(16, MVT::i32);
11484   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11485                              CstShift, CstShift, CstShift, CstShift};
11486   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11487                                     makeArrayRef(&CstShiftArray[0], NumElts));
11488   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11489
11490   SDValue Low, High;
11491   if (Subtarget.hasSSE41()) {
11492     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11493     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11494     SDValue VecCstLowBitcast =
11495         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11496     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11497     // Low will be bitcasted right away, so do not bother bitcasting back to its
11498     // original type.
11499     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11500                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11501     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11502     //                                 (uint4) 0x53000000, 0xaa);
11503     SDValue VecCstHighBitcast =
11504         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11505     SDValue VecShiftBitcast =
11506         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11507     // High will be bitcasted right away, so do not bother bitcasting back to
11508     // its original type.
11509     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11510                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11511   } else {
11512     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11513     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11514                                      CstMask, CstMask, CstMask);
11515     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11516     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11517     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11518
11519     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11520     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11521   }
11522
11523   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11524   SDValue CstFAdd = DAG.getConstantFP(
11525       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11526   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11527                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11528   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11529                                    makeArrayRef(&CstFAddArray[0], NumElts));
11530
11531   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11532   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11533   SDValue FHigh =
11534       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11535   //     return (float4) lo + fhi;
11536   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11537   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11538 }
11539
11540 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11541                                                SelectionDAG &DAG) const {
11542   SDValue N0 = Op.getOperand(0);
11543   MVT SVT = N0.getSimpleValueType();
11544   SDLoc dl(Op);
11545
11546   switch (SVT.SimpleTy) {
11547   default:
11548     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11549   case MVT::v4i8:
11550   case MVT::v4i16:
11551   case MVT::v8i8:
11552   case MVT::v8i16: {
11553     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11554     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11555                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11556   }
11557   case MVT::v4i32:
11558   case MVT::v8i32:
11559     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11560   }
11561   llvm_unreachable(nullptr);
11562 }
11563
11564 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11565                                            SelectionDAG &DAG) const {
11566   SDValue N0 = Op.getOperand(0);
11567   SDLoc dl(Op);
11568
11569   if (Op.getValueType().isVector())
11570     return lowerUINT_TO_FP_vec(Op, DAG);
11571
11572   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11573   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11574   // the optimization here.
11575   if (DAG.SignBitIsZero(N0))
11576     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11577
11578   MVT SrcVT = N0.getSimpleValueType();
11579   MVT DstVT = Op.getSimpleValueType();
11580   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11581     return LowerUINT_TO_FP_i64(Op, DAG);
11582   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11583     return LowerUINT_TO_FP_i32(Op, DAG);
11584   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11585     return SDValue();
11586
11587   // Make a 64-bit buffer, and use it to build an FILD.
11588   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11589   if (SrcVT == MVT::i32) {
11590     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11591     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11592                                      getPointerTy(), StackSlot, WordOff);
11593     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11594                                   StackSlot, MachinePointerInfo(),
11595                                   false, false, 0);
11596     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11597                                   OffsetSlot, MachinePointerInfo(),
11598                                   false, false, 0);
11599     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11600     return Fild;
11601   }
11602
11603   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11604   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11605                                StackSlot, MachinePointerInfo(),
11606                                false, false, 0);
11607   // For i64 source, we need to add the appropriate power of 2 if the input
11608   // was negative.  This is the same as the optimization in
11609   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11610   // we must be careful to do the computation in x87 extended precision, not
11611   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11612   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11613   MachineMemOperand *MMO =
11614     DAG.getMachineFunction()
11615     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11616                           MachineMemOperand::MOLoad, 8, 8);
11617
11618   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11619   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11620   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11621                                          MVT::i64, MMO);
11622
11623   APInt FF(32, 0x5F800000ULL);
11624
11625   // Check whether the sign bit is set.
11626   SDValue SignSet = DAG.getSetCC(dl,
11627                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11628                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11629                                  ISD::SETLT);
11630
11631   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11632   SDValue FudgePtr = DAG.getConstantPool(
11633                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11634                                          getPointerTy());
11635
11636   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11637   SDValue Zero = DAG.getIntPtrConstant(0);
11638   SDValue Four = DAG.getIntPtrConstant(4);
11639   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11640                                Zero, Four);
11641   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11642
11643   // Load the value out, extending it from f32 to f80.
11644   // FIXME: Avoid the extend by constructing the right constant pool?
11645   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11646                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11647                                  MVT::f32, false, false, false, 4);
11648   // Extend everything to 80 bits to force it to be done on x87.
11649   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11650   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11651 }
11652
11653 std::pair<SDValue,SDValue>
11654 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11655                                     bool IsSigned, bool IsReplace) const {
11656   SDLoc DL(Op);
11657
11658   EVT DstTy = Op.getValueType();
11659
11660   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11661     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11662     DstTy = MVT::i64;
11663   }
11664
11665   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11666          DstTy.getSimpleVT() >= MVT::i16 &&
11667          "Unknown FP_TO_INT to lower!");
11668
11669   // These are really Legal.
11670   if (DstTy == MVT::i32 &&
11671       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11672     return std::make_pair(SDValue(), SDValue());
11673   if (Subtarget->is64Bit() &&
11674       DstTy == MVT::i64 &&
11675       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11676     return std::make_pair(SDValue(), SDValue());
11677
11678   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11679   // stack slot, or into the FTOL runtime function.
11680   MachineFunction &MF = DAG.getMachineFunction();
11681   unsigned MemSize = DstTy.getSizeInBits()/8;
11682   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11683   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11684
11685   unsigned Opc;
11686   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11687     Opc = X86ISD::WIN_FTOL;
11688   else
11689     switch (DstTy.getSimpleVT().SimpleTy) {
11690     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11691     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11692     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11693     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11694     }
11695
11696   SDValue Chain = DAG.getEntryNode();
11697   SDValue Value = Op.getOperand(0);
11698   EVT TheVT = Op.getOperand(0).getValueType();
11699   // FIXME This causes a redundant load/store if the SSE-class value is already
11700   // in memory, such as if it is on the callstack.
11701   if (isScalarFPTypeInSSEReg(TheVT)) {
11702     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11703     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11704                          MachinePointerInfo::getFixedStack(SSFI),
11705                          false, false, 0);
11706     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11707     SDValue Ops[] = {
11708       Chain, StackSlot, DAG.getValueType(TheVT)
11709     };
11710
11711     MachineMemOperand *MMO =
11712       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11713                               MachineMemOperand::MOLoad, MemSize, MemSize);
11714     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11715     Chain = Value.getValue(1);
11716     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11717     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11718   }
11719
11720   MachineMemOperand *MMO =
11721     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11722                             MachineMemOperand::MOStore, MemSize, MemSize);
11723
11724   if (Opc != X86ISD::WIN_FTOL) {
11725     // Build the FP_TO_INT*_IN_MEM
11726     SDValue Ops[] = { Chain, Value, StackSlot };
11727     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11728                                            Ops, DstTy, MMO);
11729     return std::make_pair(FIST, StackSlot);
11730   } else {
11731     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11732       DAG.getVTList(MVT::Other, MVT::Glue),
11733       Chain, Value);
11734     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11735       MVT::i32, ftol.getValue(1));
11736     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11737       MVT::i32, eax.getValue(2));
11738     SDValue Ops[] = { eax, edx };
11739     SDValue pair = IsReplace
11740       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11741       : DAG.getMergeValues(Ops, DL);
11742     return std::make_pair(pair, SDValue());
11743   }
11744 }
11745
11746 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11747                               const X86Subtarget *Subtarget) {
11748   MVT VT = Op->getSimpleValueType(0);
11749   SDValue In = Op->getOperand(0);
11750   MVT InVT = In.getSimpleValueType();
11751   SDLoc dl(Op);
11752
11753   // Optimize vectors in AVX mode:
11754   //
11755   //   v8i16 -> v8i32
11756   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11757   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11758   //   Concat upper and lower parts.
11759   //
11760   //   v4i32 -> v4i64
11761   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11762   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11763   //   Concat upper and lower parts.
11764   //
11765
11766   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11767       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11768       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11769     return SDValue();
11770
11771   if (Subtarget->hasInt256())
11772     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11773
11774   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11775   SDValue Undef = DAG.getUNDEF(InVT);
11776   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11777   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11778   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11779
11780   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11781                              VT.getVectorNumElements()/2);
11782
11783   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11784   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11785
11786   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11787 }
11788
11789 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11790                                         SelectionDAG &DAG) {
11791   MVT VT = Op->getSimpleValueType(0);
11792   SDValue In = Op->getOperand(0);
11793   MVT InVT = In.getSimpleValueType();
11794   SDLoc DL(Op);
11795   unsigned int NumElts = VT.getVectorNumElements();
11796   if (NumElts != 8 && NumElts != 16)
11797     return SDValue();
11798
11799   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11800     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11801
11802   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11804   // Now we have only mask extension
11805   assert(InVT.getVectorElementType() == MVT::i1);
11806   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11807   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11808   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11809   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11810   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11811                            MachinePointerInfo::getConstantPool(),
11812                            false, false, false, Alignment);
11813
11814   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11815   if (VT.is512BitVector())
11816     return Brcst;
11817   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11818 }
11819
11820 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11821                                SelectionDAG &DAG) {
11822   if (Subtarget->hasFp256()) {
11823     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11824     if (Res.getNode())
11825       return Res;
11826   }
11827
11828   return SDValue();
11829 }
11830
11831 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11832                                 SelectionDAG &DAG) {
11833   SDLoc DL(Op);
11834   MVT VT = Op.getSimpleValueType();
11835   SDValue In = Op.getOperand(0);
11836   MVT SVT = In.getSimpleValueType();
11837
11838   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11839     return LowerZERO_EXTEND_AVX512(Op, DAG);
11840
11841   if (Subtarget->hasFp256()) {
11842     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11843     if (Res.getNode())
11844       return Res;
11845   }
11846
11847   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11848          VT.getVectorNumElements() != SVT.getVectorNumElements());
11849   return SDValue();
11850 }
11851
11852 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11853   SDLoc DL(Op);
11854   MVT VT = Op.getSimpleValueType();
11855   SDValue In = Op.getOperand(0);
11856   MVT InVT = In.getSimpleValueType();
11857
11858   if (VT == MVT::i1) {
11859     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11860            "Invalid scalar TRUNCATE operation");
11861     if (InVT.getSizeInBits() >= 32)
11862       return SDValue();
11863     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11864     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11865   }
11866   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11867          "Invalid TRUNCATE operation");
11868
11869   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11870     if (VT.getVectorElementType().getSizeInBits() >=8)
11871       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11872
11873     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11874     unsigned NumElts = InVT.getVectorNumElements();
11875     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11876     if (InVT.getSizeInBits() < 512) {
11877       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11878       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11879       InVT = ExtVT;
11880     }
11881
11882     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11883     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11884     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11885     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11886     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11887                            MachinePointerInfo::getConstantPool(),
11888                            false, false, false, Alignment);
11889     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11890     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11891     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11892   }
11893
11894   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11895     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11896     if (Subtarget->hasInt256()) {
11897       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11898       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11899       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11900                                 ShufMask);
11901       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11902                          DAG.getIntPtrConstant(0));
11903     }
11904
11905     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11906                                DAG.getIntPtrConstant(0));
11907     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11908                                DAG.getIntPtrConstant(2));
11909     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11910     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11911     static const int ShufMask[] = {0, 2, 4, 6};
11912     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11913   }
11914
11915   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11916     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11917     if (Subtarget->hasInt256()) {
11918       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11919
11920       SmallVector<SDValue,32> pshufbMask;
11921       for (unsigned i = 0; i < 2; ++i) {
11922         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11923         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11924         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11925         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11926         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11927         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11928         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11929         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11930         for (unsigned j = 0; j < 8; ++j)
11931           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11932       }
11933       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11934       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11935       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11936
11937       static const int ShufMask[] = {0,  2,  -1,  -1};
11938       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11939                                 &ShufMask[0]);
11940       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11941                        DAG.getIntPtrConstant(0));
11942       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11943     }
11944
11945     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11946                                DAG.getIntPtrConstant(0));
11947
11948     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11949                                DAG.getIntPtrConstant(4));
11950
11951     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11952     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11953
11954     // The PSHUFB mask:
11955     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11956                                    -1, -1, -1, -1, -1, -1, -1, -1};
11957
11958     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11959     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11960     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11961
11962     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11963     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11964
11965     // The MOVLHPS Mask:
11966     static const int ShufMask2[] = {0, 1, 4, 5};
11967     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11968     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11969   }
11970
11971   // Handle truncation of V256 to V128 using shuffles.
11972   if (!VT.is128BitVector() || !InVT.is256BitVector())
11973     return SDValue();
11974
11975   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11976
11977   unsigned NumElems = VT.getVectorNumElements();
11978   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11979
11980   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11981   // Prepare truncation shuffle mask
11982   for (unsigned i = 0; i != NumElems; ++i)
11983     MaskVec[i] = i * 2;
11984   SDValue V = DAG.getVectorShuffle(NVT, DL,
11985                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11986                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11987   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11988                      DAG.getIntPtrConstant(0));
11989 }
11990
11991 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11992                                            SelectionDAG &DAG) const {
11993   assert(!Op.getSimpleValueType().isVector());
11994
11995   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11996     /*IsSigned=*/ true, /*IsReplace=*/ false);
11997   SDValue FIST = Vals.first, StackSlot = Vals.second;
11998   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11999   if (!FIST.getNode()) return Op;
12000
12001   if (StackSlot.getNode())
12002     // Load the result.
12003     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12004                        FIST, StackSlot, MachinePointerInfo(),
12005                        false, false, false, 0);
12006
12007   // The node is the result.
12008   return FIST;
12009 }
12010
12011 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12012                                            SelectionDAG &DAG) const {
12013   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12014     /*IsSigned=*/ false, /*IsReplace=*/ false);
12015   SDValue FIST = Vals.first, StackSlot = Vals.second;
12016   assert(FIST.getNode() && "Unexpected failure");
12017
12018   if (StackSlot.getNode())
12019     // Load the result.
12020     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12021                        FIST, StackSlot, MachinePointerInfo(),
12022                        false, false, false, 0);
12023
12024   // The node is the result.
12025   return FIST;
12026 }
12027
12028 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12029   SDLoc DL(Op);
12030   MVT VT = Op.getSimpleValueType();
12031   SDValue In = Op.getOperand(0);
12032   MVT SVT = In.getSimpleValueType();
12033
12034   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12035
12036   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12037                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12038                                  In, DAG.getUNDEF(SVT)));
12039 }
12040
12041 /// The only differences between FABS and FNEG are the mask and the logic op.
12042 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12043 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12044   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12045          "Wrong opcode for lowering FABS or FNEG.");
12046
12047   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12048
12049   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12050   // into an FNABS. We'll lower the FABS after that if it is still in use.
12051   if (IsFABS)
12052     for (SDNode *User : Op->uses())
12053       if (User->getOpcode() == ISD::FNEG)
12054         return Op;
12055
12056   SDValue Op0 = Op.getOperand(0);
12057   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12058
12059   SDLoc dl(Op);
12060   MVT VT = Op.getSimpleValueType();
12061   // Assume scalar op for initialization; update for vector if needed.
12062   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12063   // generate a 16-byte vector constant and logic op even for the scalar case.
12064   // Using a 16-byte mask allows folding the load of the mask with
12065   // the logic op, so it can save (~4 bytes) on code size.
12066   MVT EltVT = VT;
12067   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12068   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12069   // decide if we should generate a 16-byte constant mask when we only need 4 or
12070   // 8 bytes for the scalar case.
12071   if (VT.isVector()) {
12072     EltVT = VT.getVectorElementType();
12073     NumElts = VT.getVectorNumElements();
12074   }
12075
12076   unsigned EltBits = EltVT.getSizeInBits();
12077   LLVMContext *Context = DAG.getContext();
12078   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12079   APInt MaskElt =
12080     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12081   Constant *C = ConstantInt::get(*Context, MaskElt);
12082   C = ConstantVector::getSplat(NumElts, C);
12083   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12084   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12085   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12086   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12087                              MachinePointerInfo::getConstantPool(),
12088                              false, false, false, Alignment);
12089
12090   if (VT.isVector()) {
12091     // For a vector, cast operands to a vector type, perform the logic op,
12092     // and cast the result back to the original value type.
12093     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12094     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12095     SDValue Operand = IsFNABS ?
12096       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12097       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12098     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12099     return DAG.getNode(ISD::BITCAST, dl, VT,
12100                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12101   }
12102
12103   // If not vector, then scalar.
12104   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12105   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12106   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12107 }
12108
12109 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12110   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12111   LLVMContext *Context = DAG.getContext();
12112   SDValue Op0 = Op.getOperand(0);
12113   SDValue Op1 = Op.getOperand(1);
12114   SDLoc dl(Op);
12115   MVT VT = Op.getSimpleValueType();
12116   MVT SrcVT = Op1.getSimpleValueType();
12117
12118   // If second operand is smaller, extend it first.
12119   if (SrcVT.bitsLT(VT)) {
12120     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12121     SrcVT = VT;
12122   }
12123   // And if it is bigger, shrink it first.
12124   if (SrcVT.bitsGT(VT)) {
12125     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12126     SrcVT = VT;
12127   }
12128
12129   // At this point the operands and the result should have the same
12130   // type, and that won't be f80 since that is not custom lowered.
12131
12132   const fltSemantics &Sem =
12133       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12134   const unsigned SizeInBits = VT.getSizeInBits();
12135
12136   SmallVector<Constant *, 4> CV(
12137       VT == MVT::f64 ? 2 : 4,
12138       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12139
12140   // First, clear all bits but the sign bit from the second operand (sign).
12141   CV[0] = ConstantFP::get(*Context,
12142                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12143   Constant *C = ConstantVector::get(CV);
12144   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12145   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12146                               MachinePointerInfo::getConstantPool(),
12147                               false, false, false, 16);
12148   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12149
12150   // Next, clear the sign bit from the first operand (magnitude).
12151   // If it's a constant, we can clear it here.
12152   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12153     APFloat APF = Op0CN->getValueAPF();
12154     // If the magnitude is a positive zero, the sign bit alone is enough.
12155     if (APF.isPosZero())
12156       return SignBit;
12157     APF.clearSign();
12158     CV[0] = ConstantFP::get(*Context, APF);
12159   } else {
12160     CV[0] = ConstantFP::get(
12161         *Context,
12162         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12163   }
12164   C = ConstantVector::get(CV);
12165   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12166   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12167                             MachinePointerInfo::getConstantPool(),
12168                             false, false, false, 16);
12169   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12170   if (!isa<ConstantFPSDNode>(Op0))
12171     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12172
12173   // OR the magnitude value with the sign bit.
12174   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12175 }
12176
12177 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12178   SDValue N0 = Op.getOperand(0);
12179   SDLoc dl(Op);
12180   MVT VT = Op.getSimpleValueType();
12181
12182   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12183   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12184                                   DAG.getConstant(1, VT));
12185   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12186 }
12187
12188 // Check whether an OR'd tree is PTEST-able.
12189 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12190                                       SelectionDAG &DAG) {
12191   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12192
12193   if (!Subtarget->hasSSE41())
12194     return SDValue();
12195
12196   if (!Op->hasOneUse())
12197     return SDValue();
12198
12199   SDNode *N = Op.getNode();
12200   SDLoc DL(N);
12201
12202   SmallVector<SDValue, 8> Opnds;
12203   DenseMap<SDValue, unsigned> VecInMap;
12204   SmallVector<SDValue, 8> VecIns;
12205   EVT VT = MVT::Other;
12206
12207   // Recognize a special case where a vector is casted into wide integer to
12208   // test all 0s.
12209   Opnds.push_back(N->getOperand(0));
12210   Opnds.push_back(N->getOperand(1));
12211
12212   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12213     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12214     // BFS traverse all OR'd operands.
12215     if (I->getOpcode() == ISD::OR) {
12216       Opnds.push_back(I->getOperand(0));
12217       Opnds.push_back(I->getOperand(1));
12218       // Re-evaluate the number of nodes to be traversed.
12219       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12220       continue;
12221     }
12222
12223     // Quit if a non-EXTRACT_VECTOR_ELT
12224     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12225       return SDValue();
12226
12227     // Quit if without a constant index.
12228     SDValue Idx = I->getOperand(1);
12229     if (!isa<ConstantSDNode>(Idx))
12230       return SDValue();
12231
12232     SDValue ExtractedFromVec = I->getOperand(0);
12233     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12234     if (M == VecInMap.end()) {
12235       VT = ExtractedFromVec.getValueType();
12236       // Quit if not 128/256-bit vector.
12237       if (!VT.is128BitVector() && !VT.is256BitVector())
12238         return SDValue();
12239       // Quit if not the same type.
12240       if (VecInMap.begin() != VecInMap.end() &&
12241           VT != VecInMap.begin()->first.getValueType())
12242         return SDValue();
12243       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12244       VecIns.push_back(ExtractedFromVec);
12245     }
12246     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12247   }
12248
12249   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12250          "Not extracted from 128-/256-bit vector.");
12251
12252   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12253
12254   for (DenseMap<SDValue, unsigned>::const_iterator
12255         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12256     // Quit if not all elements are used.
12257     if (I->second != FullMask)
12258       return SDValue();
12259   }
12260
12261   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12262
12263   // Cast all vectors into TestVT for PTEST.
12264   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12265     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12266
12267   // If more than one full vectors are evaluated, OR them first before PTEST.
12268   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12269     // Each iteration will OR 2 nodes and append the result until there is only
12270     // 1 node left, i.e. the final OR'd value of all vectors.
12271     SDValue LHS = VecIns[Slot];
12272     SDValue RHS = VecIns[Slot + 1];
12273     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12274   }
12275
12276   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12277                      VecIns.back(), VecIns.back());
12278 }
12279
12280 /// \brief return true if \c Op has a use that doesn't just read flags.
12281 static bool hasNonFlagsUse(SDValue Op) {
12282   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12283        ++UI) {
12284     SDNode *User = *UI;
12285     unsigned UOpNo = UI.getOperandNo();
12286     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12287       // Look pass truncate.
12288       UOpNo = User->use_begin().getOperandNo();
12289       User = *User->use_begin();
12290     }
12291
12292     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12293         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12294       return true;
12295   }
12296   return false;
12297 }
12298
12299 /// Emit nodes that will be selected as "test Op0,Op0", or something
12300 /// equivalent.
12301 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12302                                     SelectionDAG &DAG) const {
12303   if (Op.getValueType() == MVT::i1) {
12304     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12305     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12306                        DAG.getConstant(0, MVT::i8));
12307   }
12308   // CF and OF aren't always set the way we want. Determine which
12309   // of these we need.
12310   bool NeedCF = false;
12311   bool NeedOF = false;
12312   switch (X86CC) {
12313   default: break;
12314   case X86::COND_A: case X86::COND_AE:
12315   case X86::COND_B: case X86::COND_BE:
12316     NeedCF = true;
12317     break;
12318   case X86::COND_G: case X86::COND_GE:
12319   case X86::COND_L: case X86::COND_LE:
12320   case X86::COND_O: case X86::COND_NO: {
12321     // Check if we really need to set the
12322     // Overflow flag. If NoSignedWrap is present
12323     // that is not actually needed.
12324     switch (Op->getOpcode()) {
12325     case ISD::ADD:
12326     case ISD::SUB:
12327     case ISD::MUL:
12328     case ISD::SHL: {
12329       const BinaryWithFlagsSDNode *BinNode =
12330           cast<BinaryWithFlagsSDNode>(Op.getNode());
12331       if (BinNode->hasNoSignedWrap())
12332         break;
12333     }
12334     default:
12335       NeedOF = true;
12336       break;
12337     }
12338     break;
12339   }
12340   }
12341   // See if we can use the EFLAGS value from the operand instead of
12342   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12343   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12344   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12345     // Emit a CMP with 0, which is the TEST pattern.
12346     //if (Op.getValueType() == MVT::i1)
12347     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12348     //                     DAG.getConstant(0, MVT::i1));
12349     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12350                        DAG.getConstant(0, Op.getValueType()));
12351   }
12352   unsigned Opcode = 0;
12353   unsigned NumOperands = 0;
12354
12355   // Truncate operations may prevent the merge of the SETCC instruction
12356   // and the arithmetic instruction before it. Attempt to truncate the operands
12357   // of the arithmetic instruction and use a reduced bit-width instruction.
12358   bool NeedTruncation = false;
12359   SDValue ArithOp = Op;
12360   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12361     SDValue Arith = Op->getOperand(0);
12362     // Both the trunc and the arithmetic op need to have one user each.
12363     if (Arith->hasOneUse())
12364       switch (Arith.getOpcode()) {
12365         default: break;
12366         case ISD::ADD:
12367         case ISD::SUB:
12368         case ISD::AND:
12369         case ISD::OR:
12370         case ISD::XOR: {
12371           NeedTruncation = true;
12372           ArithOp = Arith;
12373         }
12374       }
12375   }
12376
12377   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12378   // which may be the result of a CAST.  We use the variable 'Op', which is the
12379   // non-casted variable when we check for possible users.
12380   switch (ArithOp.getOpcode()) {
12381   case ISD::ADD:
12382     // Due to an isel shortcoming, be conservative if this add is likely to be
12383     // selected as part of a load-modify-store instruction. When the root node
12384     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12385     // uses of other nodes in the match, such as the ADD in this case. This
12386     // leads to the ADD being left around and reselected, with the result being
12387     // two adds in the output.  Alas, even if none our users are stores, that
12388     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12389     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12390     // climbing the DAG back to the root, and it doesn't seem to be worth the
12391     // effort.
12392     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12393          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12394       if (UI->getOpcode() != ISD::CopyToReg &&
12395           UI->getOpcode() != ISD::SETCC &&
12396           UI->getOpcode() != ISD::STORE)
12397         goto default_case;
12398
12399     if (ConstantSDNode *C =
12400         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12401       // An add of one will be selected as an INC.
12402       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12403         Opcode = X86ISD::INC;
12404         NumOperands = 1;
12405         break;
12406       }
12407
12408       // An add of negative one (subtract of one) will be selected as a DEC.
12409       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12410         Opcode = X86ISD::DEC;
12411         NumOperands = 1;
12412         break;
12413       }
12414     }
12415
12416     // Otherwise use a regular EFLAGS-setting add.
12417     Opcode = X86ISD::ADD;
12418     NumOperands = 2;
12419     break;
12420   case ISD::SHL:
12421   case ISD::SRL:
12422     // If we have a constant logical shift that's only used in a comparison
12423     // against zero turn it into an equivalent AND. This allows turning it into
12424     // a TEST instruction later.
12425     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12426         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12427       EVT VT = Op.getValueType();
12428       unsigned BitWidth = VT.getSizeInBits();
12429       unsigned ShAmt = Op->getConstantOperandVal(1);
12430       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12431         break;
12432       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12433                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12434                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12435       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12436         break;
12437       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12438                                 DAG.getConstant(Mask, VT));
12439       DAG.ReplaceAllUsesWith(Op, New);
12440       Op = New;
12441     }
12442     break;
12443
12444   case ISD::AND:
12445     // If the primary and result isn't used, don't bother using X86ISD::AND,
12446     // because a TEST instruction will be better.
12447     if (!hasNonFlagsUse(Op))
12448       break;
12449     // FALL THROUGH
12450   case ISD::SUB:
12451   case ISD::OR:
12452   case ISD::XOR:
12453     // Due to the ISEL shortcoming noted above, be conservative if this op is
12454     // likely to be selected as part of a load-modify-store instruction.
12455     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12456            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12457       if (UI->getOpcode() == ISD::STORE)
12458         goto default_case;
12459
12460     // Otherwise use a regular EFLAGS-setting instruction.
12461     switch (ArithOp.getOpcode()) {
12462     default: llvm_unreachable("unexpected operator!");
12463     case ISD::SUB: Opcode = X86ISD::SUB; break;
12464     case ISD::XOR: Opcode = X86ISD::XOR; break;
12465     case ISD::AND: Opcode = X86ISD::AND; break;
12466     case ISD::OR: {
12467       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12468         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12469         if (EFLAGS.getNode())
12470           return EFLAGS;
12471       }
12472       Opcode = X86ISD::OR;
12473       break;
12474     }
12475     }
12476
12477     NumOperands = 2;
12478     break;
12479   case X86ISD::ADD:
12480   case X86ISD::SUB:
12481   case X86ISD::INC:
12482   case X86ISD::DEC:
12483   case X86ISD::OR:
12484   case X86ISD::XOR:
12485   case X86ISD::AND:
12486     return SDValue(Op.getNode(), 1);
12487   default:
12488   default_case:
12489     break;
12490   }
12491
12492   // If we found that truncation is beneficial, perform the truncation and
12493   // update 'Op'.
12494   if (NeedTruncation) {
12495     EVT VT = Op.getValueType();
12496     SDValue WideVal = Op->getOperand(0);
12497     EVT WideVT = WideVal.getValueType();
12498     unsigned ConvertedOp = 0;
12499     // Use a target machine opcode to prevent further DAGCombine
12500     // optimizations that may separate the arithmetic operations
12501     // from the setcc node.
12502     switch (WideVal.getOpcode()) {
12503       default: break;
12504       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12505       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12506       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12507       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12508       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12509     }
12510
12511     if (ConvertedOp) {
12512       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12513       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12514         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12515         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12516         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12517       }
12518     }
12519   }
12520
12521   if (Opcode == 0)
12522     // Emit a CMP with 0, which is the TEST pattern.
12523     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12524                        DAG.getConstant(0, Op.getValueType()));
12525
12526   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12527   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12528
12529   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12530   DAG.ReplaceAllUsesWith(Op, New);
12531   return SDValue(New.getNode(), 1);
12532 }
12533
12534 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12535 /// equivalent.
12536 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12537                                    SDLoc dl, SelectionDAG &DAG) const {
12538   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12539     if (C->getAPIntValue() == 0)
12540       return EmitTest(Op0, X86CC, dl, DAG);
12541
12542      if (Op0.getValueType() == MVT::i1)
12543        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12544   }
12545
12546   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12547        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12548     // Do the comparison at i32 if it's smaller, besides the Atom case.
12549     // This avoids subregister aliasing issues. Keep the smaller reference
12550     // if we're optimizing for size, however, as that'll allow better folding
12551     // of memory operations.
12552     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12553         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12554             Attribute::MinSize) &&
12555         !Subtarget->isAtom()) {
12556       unsigned ExtendOp =
12557           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12558       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12559       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12560     }
12561     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12562     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12563     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12564                               Op0, Op1);
12565     return SDValue(Sub.getNode(), 1);
12566   }
12567   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12568 }
12569
12570 /// Convert a comparison if required by the subtarget.
12571 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12572                                                  SelectionDAG &DAG) const {
12573   // If the subtarget does not support the FUCOMI instruction, floating-point
12574   // comparisons have to be converted.
12575   if (Subtarget->hasCMov() ||
12576       Cmp.getOpcode() != X86ISD::CMP ||
12577       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12578       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12579     return Cmp;
12580
12581   // The instruction selector will select an FUCOM instruction instead of
12582   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12583   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12584   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12585   SDLoc dl(Cmp);
12586   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12587   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12588   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12589                             DAG.getConstant(8, MVT::i8));
12590   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12591   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12592 }
12593
12594 /// The minimum architected relative accuracy is 2^-12. We need one
12595 /// Newton-Raphson step to have a good float result (24 bits of precision).
12596 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12597                                             DAGCombinerInfo &DCI,
12598                                             unsigned &RefinementSteps,
12599                                             bool &UseOneConstNR) const {
12600   // FIXME: We should use instruction latency models to calculate the cost of
12601   // each potential sequence, but this is very hard to do reliably because
12602   // at least Intel's Core* chips have variable timing based on the number of
12603   // significant digits in the divisor and/or sqrt operand.
12604   if (!Subtarget->useSqrtEst())
12605     return SDValue();
12606
12607   EVT VT = Op.getValueType();
12608
12609   // SSE1 has rsqrtss and rsqrtps.
12610   // TODO: Add support for AVX512 (v16f32).
12611   // It is likely not profitable to do this for f64 because a double-precision
12612   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12613   // instructions: convert to single, rsqrtss, convert back to double, refine
12614   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12615   // along with FMA, this could be a throughput win.
12616   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12617       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12618     RefinementSteps = 1;
12619     UseOneConstNR = false;
12620     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12621   }
12622   return SDValue();
12623 }
12624
12625 /// The minimum architected relative accuracy is 2^-12. We need one
12626 /// Newton-Raphson step to have a good float result (24 bits of precision).
12627 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12628                                             DAGCombinerInfo &DCI,
12629                                             unsigned &RefinementSteps) const {
12630   // FIXME: We should use instruction latency models to calculate the cost of
12631   // each potential sequence, but this is very hard to do reliably because
12632   // at least Intel's Core* chips have variable timing based on the number of
12633   // significant digits in the divisor.
12634   if (!Subtarget->useReciprocalEst())
12635     return SDValue();
12636
12637   EVT VT = Op.getValueType();
12638
12639   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12640   // TODO: Add support for AVX512 (v16f32).
12641   // It is likely not profitable to do this for f64 because a double-precision
12642   // reciprocal estimate with refinement on x86 prior to FMA requires
12643   // 15 instructions: convert to single, rcpss, convert back to double, refine
12644   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12645   // along with FMA, this could be a throughput win.
12646   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12647       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12648     RefinementSteps = ReciprocalEstimateRefinementSteps;
12649     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12650   }
12651   return SDValue();
12652 }
12653
12654 static bool isAllOnes(SDValue V) {
12655   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12656   return C && C->isAllOnesValue();
12657 }
12658
12659 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12660 /// if it's possible.
12661 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12662                                      SDLoc dl, SelectionDAG &DAG) const {
12663   SDValue Op0 = And.getOperand(0);
12664   SDValue Op1 = And.getOperand(1);
12665   if (Op0.getOpcode() == ISD::TRUNCATE)
12666     Op0 = Op0.getOperand(0);
12667   if (Op1.getOpcode() == ISD::TRUNCATE)
12668     Op1 = Op1.getOperand(0);
12669
12670   SDValue LHS, RHS;
12671   if (Op1.getOpcode() == ISD::SHL)
12672     std::swap(Op0, Op1);
12673   if (Op0.getOpcode() == ISD::SHL) {
12674     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12675       if (And00C->getZExtValue() == 1) {
12676         // If we looked past a truncate, check that it's only truncating away
12677         // known zeros.
12678         unsigned BitWidth = Op0.getValueSizeInBits();
12679         unsigned AndBitWidth = And.getValueSizeInBits();
12680         if (BitWidth > AndBitWidth) {
12681           APInt Zeros, Ones;
12682           DAG.computeKnownBits(Op0, Zeros, Ones);
12683           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12684             return SDValue();
12685         }
12686         LHS = Op1;
12687         RHS = Op0.getOperand(1);
12688       }
12689   } else if (Op1.getOpcode() == ISD::Constant) {
12690     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12691     uint64_t AndRHSVal = AndRHS->getZExtValue();
12692     SDValue AndLHS = Op0;
12693
12694     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12695       LHS = AndLHS.getOperand(0);
12696       RHS = AndLHS.getOperand(1);
12697     }
12698
12699     // Use BT if the immediate can't be encoded in a TEST instruction.
12700     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12701       LHS = AndLHS;
12702       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12703     }
12704   }
12705
12706   if (LHS.getNode()) {
12707     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12708     // instruction.  Since the shift amount is in-range-or-undefined, we know
12709     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12710     // the encoding for the i16 version is larger than the i32 version.
12711     // Also promote i16 to i32 for performance / code size reason.
12712     if (LHS.getValueType() == MVT::i8 ||
12713         LHS.getValueType() == MVT::i16)
12714       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12715
12716     // If the operand types disagree, extend the shift amount to match.  Since
12717     // BT ignores high bits (like shifts) we can use anyextend.
12718     if (LHS.getValueType() != RHS.getValueType())
12719       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12720
12721     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12722     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12723     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12724                        DAG.getConstant(Cond, MVT::i8), BT);
12725   }
12726
12727   return SDValue();
12728 }
12729
12730 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12731 /// mask CMPs.
12732 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12733                               SDValue &Op1) {
12734   unsigned SSECC;
12735   bool Swap = false;
12736
12737   // SSE Condition code mapping:
12738   //  0 - EQ
12739   //  1 - LT
12740   //  2 - LE
12741   //  3 - UNORD
12742   //  4 - NEQ
12743   //  5 - NLT
12744   //  6 - NLE
12745   //  7 - ORD
12746   switch (SetCCOpcode) {
12747   default: llvm_unreachable("Unexpected SETCC condition");
12748   case ISD::SETOEQ:
12749   case ISD::SETEQ:  SSECC = 0; break;
12750   case ISD::SETOGT:
12751   case ISD::SETGT:  Swap = true; // Fallthrough
12752   case ISD::SETLT:
12753   case ISD::SETOLT: SSECC = 1; break;
12754   case ISD::SETOGE:
12755   case ISD::SETGE:  Swap = true; // Fallthrough
12756   case ISD::SETLE:
12757   case ISD::SETOLE: SSECC = 2; break;
12758   case ISD::SETUO:  SSECC = 3; break;
12759   case ISD::SETUNE:
12760   case ISD::SETNE:  SSECC = 4; break;
12761   case ISD::SETULE: Swap = true; // Fallthrough
12762   case ISD::SETUGE: SSECC = 5; break;
12763   case ISD::SETULT: Swap = true; // Fallthrough
12764   case ISD::SETUGT: SSECC = 6; break;
12765   case ISD::SETO:   SSECC = 7; break;
12766   case ISD::SETUEQ:
12767   case ISD::SETONE: SSECC = 8; break;
12768   }
12769   if (Swap)
12770     std::swap(Op0, Op1);
12771
12772   return SSECC;
12773 }
12774
12775 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12776 // ones, and then concatenate the result back.
12777 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12778   MVT VT = Op.getSimpleValueType();
12779
12780   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12781          "Unsupported value type for operation");
12782
12783   unsigned NumElems = VT.getVectorNumElements();
12784   SDLoc dl(Op);
12785   SDValue CC = Op.getOperand(2);
12786
12787   // Extract the LHS vectors
12788   SDValue LHS = Op.getOperand(0);
12789   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12790   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12791
12792   // Extract the RHS vectors
12793   SDValue RHS = Op.getOperand(1);
12794   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12795   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12796
12797   // Issue the operation on the smaller types and concatenate the result back
12798   MVT EltVT = VT.getVectorElementType();
12799   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12800   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12801                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12802                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12803 }
12804
12805 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12806                                      const X86Subtarget *Subtarget) {
12807   SDValue Op0 = Op.getOperand(0);
12808   SDValue Op1 = Op.getOperand(1);
12809   SDValue CC = Op.getOperand(2);
12810   MVT VT = Op.getSimpleValueType();
12811   SDLoc dl(Op);
12812
12813   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12814          Op.getValueType().getScalarType() == MVT::i1 &&
12815          "Cannot set masked compare for this operation");
12816
12817   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12818   unsigned  Opc = 0;
12819   bool Unsigned = false;
12820   bool Swap = false;
12821   unsigned SSECC;
12822   switch (SetCCOpcode) {
12823   default: llvm_unreachable("Unexpected SETCC condition");
12824   case ISD::SETNE:  SSECC = 4; break;
12825   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12826   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12827   case ISD::SETLT:  Swap = true; //fall-through
12828   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12829   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12830   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12831   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12832   case ISD::SETULE: Unsigned = true; //fall-through
12833   case ISD::SETLE:  SSECC = 2; break;
12834   }
12835
12836   if (Swap)
12837     std::swap(Op0, Op1);
12838   if (Opc)
12839     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12840   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12841   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12842                      DAG.getConstant(SSECC, MVT::i8));
12843 }
12844
12845 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12846 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12847 /// return an empty value.
12848 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12849 {
12850   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12851   if (!BV)
12852     return SDValue();
12853
12854   MVT VT = Op1.getSimpleValueType();
12855   MVT EVT = VT.getVectorElementType();
12856   unsigned n = VT.getVectorNumElements();
12857   SmallVector<SDValue, 8> ULTOp1;
12858
12859   for (unsigned i = 0; i < n; ++i) {
12860     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12861     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12862       return SDValue();
12863
12864     // Avoid underflow.
12865     APInt Val = Elt->getAPIntValue();
12866     if (Val == 0)
12867       return SDValue();
12868
12869     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12870   }
12871
12872   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12873 }
12874
12875 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12876                            SelectionDAG &DAG) {
12877   SDValue Op0 = Op.getOperand(0);
12878   SDValue Op1 = Op.getOperand(1);
12879   SDValue CC = Op.getOperand(2);
12880   MVT VT = Op.getSimpleValueType();
12881   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12882   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12883   SDLoc dl(Op);
12884
12885   if (isFP) {
12886 #ifndef NDEBUG
12887     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12888     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12889 #endif
12890
12891     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12892     unsigned Opc = X86ISD::CMPP;
12893     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12894       assert(VT.getVectorNumElements() <= 16);
12895       Opc = X86ISD::CMPM;
12896     }
12897     // In the two special cases we can't handle, emit two comparisons.
12898     if (SSECC == 8) {
12899       unsigned CC0, CC1;
12900       unsigned CombineOpc;
12901       if (SetCCOpcode == ISD::SETUEQ) {
12902         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12903       } else {
12904         assert(SetCCOpcode == ISD::SETONE);
12905         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12906       }
12907
12908       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12909                                  DAG.getConstant(CC0, MVT::i8));
12910       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12911                                  DAG.getConstant(CC1, MVT::i8));
12912       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12913     }
12914     // Handle all other FP comparisons here.
12915     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12916                        DAG.getConstant(SSECC, MVT::i8));
12917   }
12918
12919   // Break 256-bit integer vector compare into smaller ones.
12920   if (VT.is256BitVector() && !Subtarget->hasInt256())
12921     return Lower256IntVSETCC(Op, DAG);
12922
12923   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12924   EVT OpVT = Op1.getValueType();
12925   if (Subtarget->hasAVX512()) {
12926     if (Op1.getValueType().is512BitVector() ||
12927         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
12928         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12929       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12930
12931     // In AVX-512 architecture setcc returns mask with i1 elements,
12932     // But there is no compare instruction for i8 and i16 elements in KNL.
12933     // We are not talking about 512-bit operands in this case, these
12934     // types are illegal.
12935     if (MaskResult &&
12936         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12937          OpVT.getVectorElementType().getSizeInBits() >= 8))
12938       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12939                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12940   }
12941
12942   // We are handling one of the integer comparisons here.  Since SSE only has
12943   // GT and EQ comparisons for integer, swapping operands and multiple
12944   // operations may be required for some comparisons.
12945   unsigned Opc;
12946   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12947   bool Subus = false;
12948
12949   switch (SetCCOpcode) {
12950   default: llvm_unreachable("Unexpected SETCC condition");
12951   case ISD::SETNE:  Invert = true;
12952   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12953   case ISD::SETLT:  Swap = true;
12954   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12955   case ISD::SETGE:  Swap = true;
12956   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12957                     Invert = true; break;
12958   case ISD::SETULT: Swap = true;
12959   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12960                     FlipSigns = true; break;
12961   case ISD::SETUGE: Swap = true;
12962   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12963                     FlipSigns = true; Invert = true; break;
12964   }
12965
12966   // Special case: Use min/max operations for SETULE/SETUGE
12967   MVT VET = VT.getVectorElementType();
12968   bool hasMinMax =
12969        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12970     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12971
12972   if (hasMinMax) {
12973     switch (SetCCOpcode) {
12974     default: break;
12975     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12976     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12977     }
12978
12979     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12980   }
12981
12982   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12983   if (!MinMax && hasSubus) {
12984     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12985     // Op0 u<= Op1:
12986     //   t = psubus Op0, Op1
12987     //   pcmpeq t, <0..0>
12988     switch (SetCCOpcode) {
12989     default: break;
12990     case ISD::SETULT: {
12991       // If the comparison is against a constant we can turn this into a
12992       // setule.  With psubus, setule does not require a swap.  This is
12993       // beneficial because the constant in the register is no longer
12994       // destructed as the destination so it can be hoisted out of a loop.
12995       // Only do this pre-AVX since vpcmp* is no longer destructive.
12996       if (Subtarget->hasAVX())
12997         break;
12998       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12999       if (ULEOp1.getNode()) {
13000         Op1 = ULEOp1;
13001         Subus = true; Invert = false; Swap = false;
13002       }
13003       break;
13004     }
13005     // Psubus is better than flip-sign because it requires no inversion.
13006     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13007     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13008     }
13009
13010     if (Subus) {
13011       Opc = X86ISD::SUBUS;
13012       FlipSigns = false;
13013     }
13014   }
13015
13016   if (Swap)
13017     std::swap(Op0, Op1);
13018
13019   // Check that the operation in question is available (most are plain SSE2,
13020   // but PCMPGTQ and PCMPEQQ have different requirements).
13021   if (VT == MVT::v2i64) {
13022     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13023       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13024
13025       // First cast everything to the right type.
13026       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13027       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13028
13029       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13030       // bits of the inputs before performing those operations. The lower
13031       // compare is always unsigned.
13032       SDValue SB;
13033       if (FlipSigns) {
13034         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13035       } else {
13036         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13037         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13038         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13039                          Sign, Zero, Sign, Zero);
13040       }
13041       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13042       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13043
13044       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13045       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13046       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13047
13048       // Create masks for only the low parts/high parts of the 64 bit integers.
13049       static const int MaskHi[] = { 1, 1, 3, 3 };
13050       static const int MaskLo[] = { 0, 0, 2, 2 };
13051       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13052       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13053       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13054
13055       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13056       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13057
13058       if (Invert)
13059         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13060
13061       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13062     }
13063
13064     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13065       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13066       // pcmpeqd + pshufd + pand.
13067       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13068
13069       // First cast everything to the right type.
13070       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13071       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13072
13073       // Do the compare.
13074       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13075
13076       // Make sure the lower and upper halves are both all-ones.
13077       static const int Mask[] = { 1, 0, 3, 2 };
13078       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13079       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13080
13081       if (Invert)
13082         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13083
13084       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13085     }
13086   }
13087
13088   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13089   // bits of the inputs before performing those operations.
13090   if (FlipSigns) {
13091     EVT EltVT = VT.getVectorElementType();
13092     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13093     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13094     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13095   }
13096
13097   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13098
13099   // If the logical-not of the result is required, perform that now.
13100   if (Invert)
13101     Result = DAG.getNOT(dl, Result, VT);
13102
13103   if (MinMax)
13104     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13105
13106   if (Subus)
13107     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13108                          getZeroVector(VT, Subtarget, DAG, dl));
13109
13110   return Result;
13111 }
13112
13113 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13114
13115   MVT VT = Op.getSimpleValueType();
13116
13117   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13118
13119   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13120          && "SetCC type must be 8-bit or 1-bit integer");
13121   SDValue Op0 = Op.getOperand(0);
13122   SDValue Op1 = Op.getOperand(1);
13123   SDLoc dl(Op);
13124   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13125
13126   // Optimize to BT if possible.
13127   // Lower (X & (1 << N)) == 0 to BT(X, N).
13128   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13129   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13130   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13131       Op1.getOpcode() == ISD::Constant &&
13132       cast<ConstantSDNode>(Op1)->isNullValue() &&
13133       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13134     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13135     if (NewSetCC.getNode()) {
13136       if (VT == MVT::i1)
13137         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13138       return NewSetCC;
13139     }
13140   }
13141
13142   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13143   // these.
13144   if (Op1.getOpcode() == ISD::Constant &&
13145       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13146        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13147       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13148
13149     // If the input is a setcc, then reuse the input setcc or use a new one with
13150     // the inverted condition.
13151     if (Op0.getOpcode() == X86ISD::SETCC) {
13152       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13153       bool Invert = (CC == ISD::SETNE) ^
13154         cast<ConstantSDNode>(Op1)->isNullValue();
13155       if (!Invert)
13156         return Op0;
13157
13158       CCode = X86::GetOppositeBranchCondition(CCode);
13159       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13160                                   DAG.getConstant(CCode, MVT::i8),
13161                                   Op0.getOperand(1));
13162       if (VT == MVT::i1)
13163         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13164       return SetCC;
13165     }
13166   }
13167   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13168       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13169       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13170
13171     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13172     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13173   }
13174
13175   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13176   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13177   if (X86CC == X86::COND_INVALID)
13178     return SDValue();
13179
13180   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13181   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13182   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13183                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13184   if (VT == MVT::i1)
13185     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13186   return SetCC;
13187 }
13188
13189 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13190 static bool isX86LogicalCmp(SDValue Op) {
13191   unsigned Opc = Op.getNode()->getOpcode();
13192   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13193       Opc == X86ISD::SAHF)
13194     return true;
13195   if (Op.getResNo() == 1 &&
13196       (Opc == X86ISD::ADD ||
13197        Opc == X86ISD::SUB ||
13198        Opc == X86ISD::ADC ||
13199        Opc == X86ISD::SBB ||
13200        Opc == X86ISD::SMUL ||
13201        Opc == X86ISD::UMUL ||
13202        Opc == X86ISD::INC ||
13203        Opc == X86ISD::DEC ||
13204        Opc == X86ISD::OR ||
13205        Opc == X86ISD::XOR ||
13206        Opc == X86ISD::AND))
13207     return true;
13208
13209   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13210     return true;
13211
13212   return false;
13213 }
13214
13215 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13216   if (V.getOpcode() != ISD::TRUNCATE)
13217     return false;
13218
13219   SDValue VOp0 = V.getOperand(0);
13220   unsigned InBits = VOp0.getValueSizeInBits();
13221   unsigned Bits = V.getValueSizeInBits();
13222   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13223 }
13224
13225 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13226   bool addTest = true;
13227   SDValue Cond  = Op.getOperand(0);
13228   SDValue Op1 = Op.getOperand(1);
13229   SDValue Op2 = Op.getOperand(2);
13230   SDLoc DL(Op);
13231   EVT VT = Op1.getValueType();
13232   SDValue CC;
13233
13234   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13235   // are available or VBLENDV if AVX is available.
13236   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13237   if (Cond.getOpcode() == ISD::SETCC &&
13238       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13239        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13240       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13241     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13242     int SSECC = translateX86FSETCC(
13243         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13244
13245     if (SSECC != 8) {
13246       if (Subtarget->hasAVX512()) {
13247         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13248                                   DAG.getConstant(SSECC, MVT::i8));
13249         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13250       }
13251
13252       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13253                                 DAG.getConstant(SSECC, MVT::i8));
13254
13255       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13256       // of 3 logic instructions for size savings and potentially speed.
13257       // Unfortunately, there is no scalar form of VBLENDV.
13258       
13259       // If either operand is a constant, don't try this. We can expect to
13260       // optimize away at least one of the logic instructions later in that
13261       // case, so that sequence would be faster than a variable blend.
13262       
13263       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13264       // uses XMM0 as the selection register. That may need just as many
13265       // instructions as the AND/ANDN/OR sequence due to register moves, so
13266       // don't bother.
13267
13268       if (Subtarget->hasAVX() &&
13269           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13270         
13271         // Convert to vectors, do a VSELECT, and convert back to scalar.
13272         // All of the conversions should be optimized away.
13273         
13274         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13275         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13276         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13277         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13278
13279         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13280         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13281         
13282         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13283         
13284         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13285                            VSel, DAG.getIntPtrConstant(0));
13286       }
13287       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13288       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13289       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13290     }
13291   }
13292
13293   if (Cond.getOpcode() == ISD::SETCC) {
13294     SDValue NewCond = LowerSETCC(Cond, DAG);
13295     if (NewCond.getNode())
13296       Cond = NewCond;
13297   }
13298
13299   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13300   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13301   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13302   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13303   if (Cond.getOpcode() == X86ISD::SETCC &&
13304       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13305       isZero(Cond.getOperand(1).getOperand(1))) {
13306     SDValue Cmp = Cond.getOperand(1);
13307
13308     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13309
13310     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13311         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13312       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13313
13314       SDValue CmpOp0 = Cmp.getOperand(0);
13315       // Apply further optimizations for special cases
13316       // (select (x != 0), -1, 0) -> neg & sbb
13317       // (select (x == 0), 0, -1) -> neg & sbb
13318       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13319         if (YC->isNullValue() &&
13320             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13321           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13322           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13323                                     DAG.getConstant(0, CmpOp0.getValueType()),
13324                                     CmpOp0);
13325           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13326                                     DAG.getConstant(X86::COND_B, MVT::i8),
13327                                     SDValue(Neg.getNode(), 1));
13328           return Res;
13329         }
13330
13331       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13332                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13333       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13334
13335       SDValue Res =   // Res = 0 or -1.
13336         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13337                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13338
13339       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13340         Res = DAG.getNOT(DL, Res, Res.getValueType());
13341
13342       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13343       if (!N2C || !N2C->isNullValue())
13344         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13345       return Res;
13346     }
13347   }
13348
13349   // Look past (and (setcc_carry (cmp ...)), 1).
13350   if (Cond.getOpcode() == ISD::AND &&
13351       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13352     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13353     if (C && C->getAPIntValue() == 1)
13354       Cond = Cond.getOperand(0);
13355   }
13356
13357   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13358   // setting operand in place of the X86ISD::SETCC.
13359   unsigned CondOpcode = Cond.getOpcode();
13360   if (CondOpcode == X86ISD::SETCC ||
13361       CondOpcode == X86ISD::SETCC_CARRY) {
13362     CC = Cond.getOperand(0);
13363
13364     SDValue Cmp = Cond.getOperand(1);
13365     unsigned Opc = Cmp.getOpcode();
13366     MVT VT = Op.getSimpleValueType();
13367
13368     bool IllegalFPCMov = false;
13369     if (VT.isFloatingPoint() && !VT.isVector() &&
13370         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13371       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13372
13373     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13374         Opc == X86ISD::BT) { // FIXME
13375       Cond = Cmp;
13376       addTest = false;
13377     }
13378   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13379              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13380              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13381               Cond.getOperand(0).getValueType() != MVT::i8)) {
13382     SDValue LHS = Cond.getOperand(0);
13383     SDValue RHS = Cond.getOperand(1);
13384     unsigned X86Opcode;
13385     unsigned X86Cond;
13386     SDVTList VTs;
13387     switch (CondOpcode) {
13388     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13389     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13390     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13391     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13392     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13393     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13394     default: llvm_unreachable("unexpected overflowing operator");
13395     }
13396     if (CondOpcode == ISD::UMULO)
13397       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13398                           MVT::i32);
13399     else
13400       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13401
13402     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13403
13404     if (CondOpcode == ISD::UMULO)
13405       Cond = X86Op.getValue(2);
13406     else
13407       Cond = X86Op.getValue(1);
13408
13409     CC = DAG.getConstant(X86Cond, MVT::i8);
13410     addTest = false;
13411   }
13412
13413   if (addTest) {
13414     // Look pass the truncate if the high bits are known zero.
13415     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13416         Cond = Cond.getOperand(0);
13417
13418     // We know the result of AND is compared against zero. Try to match
13419     // it to BT.
13420     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13421       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13422       if (NewSetCC.getNode()) {
13423         CC = NewSetCC.getOperand(0);
13424         Cond = NewSetCC.getOperand(1);
13425         addTest = false;
13426       }
13427     }
13428   }
13429
13430   if (addTest) {
13431     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13432     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13433   }
13434
13435   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13436   // a <  b ?  0 : -1 -> RES = setcc_carry
13437   // a >= b ? -1 :  0 -> RES = setcc_carry
13438   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13439   if (Cond.getOpcode() == X86ISD::SUB) {
13440     Cond = ConvertCmpIfNecessary(Cond, DAG);
13441     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13442
13443     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13444         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13445       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13446                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13447       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13448         return DAG.getNOT(DL, Res, Res.getValueType());
13449       return Res;
13450     }
13451   }
13452
13453   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13454   // widen the cmov and push the truncate through. This avoids introducing a new
13455   // branch during isel and doesn't add any extensions.
13456   if (Op.getValueType() == MVT::i8 &&
13457       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13458     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13459     if (T1.getValueType() == T2.getValueType() &&
13460         // Blacklist CopyFromReg to avoid partial register stalls.
13461         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13462       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13463       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13464       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13465     }
13466   }
13467
13468   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13469   // condition is true.
13470   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13471   SDValue Ops[] = { Op2, Op1, CC, Cond };
13472   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13473 }
13474
13475 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13476                                        SelectionDAG &DAG) {
13477   MVT VT = Op->getSimpleValueType(0);
13478   SDValue In = Op->getOperand(0);
13479   MVT InVT = In.getSimpleValueType();
13480   MVT VTElt = VT.getVectorElementType();
13481   MVT InVTElt = InVT.getVectorElementType();
13482   SDLoc dl(Op);
13483
13484   // SKX processor
13485   if ((InVTElt == MVT::i1) &&
13486       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13487         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13488
13489        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13490         VTElt.getSizeInBits() <= 16)) ||
13491
13492        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13493         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13494
13495        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13496         VTElt.getSizeInBits() >= 32))))
13497     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13498
13499   unsigned int NumElts = VT.getVectorNumElements();
13500
13501   if (NumElts != 8 && NumElts != 16)
13502     return SDValue();
13503
13504   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13505     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13506       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13507     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13508   }
13509
13510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13511   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13512
13513   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13514   Constant *C = ConstantInt::get(*DAG.getContext(),
13515     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13516
13517   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13518   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13519   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13520                           MachinePointerInfo::getConstantPool(),
13521                           false, false, false, Alignment);
13522   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13523   if (VT.is512BitVector())
13524     return Brcst;
13525   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13526 }
13527
13528 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13529                                 SelectionDAG &DAG) {
13530   MVT VT = Op->getSimpleValueType(0);
13531   SDValue In = Op->getOperand(0);
13532   MVT InVT = In.getSimpleValueType();
13533   SDLoc dl(Op);
13534
13535   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13536     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13537
13538   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13539       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13540       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13541     return SDValue();
13542
13543   if (Subtarget->hasInt256())
13544     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13545
13546   // Optimize vectors in AVX mode
13547   // Sign extend  v8i16 to v8i32 and
13548   //              v4i32 to v4i64
13549   //
13550   // Divide input vector into two parts
13551   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13552   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13553   // concat the vectors to original VT
13554
13555   unsigned NumElems = InVT.getVectorNumElements();
13556   SDValue Undef = DAG.getUNDEF(InVT);
13557
13558   SmallVector<int,8> ShufMask1(NumElems, -1);
13559   for (unsigned i = 0; i != NumElems/2; ++i)
13560     ShufMask1[i] = i;
13561
13562   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13563
13564   SmallVector<int,8> ShufMask2(NumElems, -1);
13565   for (unsigned i = 0; i != NumElems/2; ++i)
13566     ShufMask2[i] = i + NumElems/2;
13567
13568   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13569
13570   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13571                                 VT.getVectorNumElements()/2);
13572
13573   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13574   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13575
13576   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13577 }
13578
13579 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13580 // may emit an illegal shuffle but the expansion is still better than scalar
13581 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13582 // we'll emit a shuffle and a arithmetic shift.
13583 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13584 // TODO: It is possible to support ZExt by zeroing the undef values during
13585 // the shuffle phase or after the shuffle.
13586 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13587                                  SelectionDAG &DAG) {
13588   MVT RegVT = Op.getSimpleValueType();
13589   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13590   assert(RegVT.isInteger() &&
13591          "We only custom lower integer vector sext loads.");
13592
13593   // Nothing useful we can do without SSE2 shuffles.
13594   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13595
13596   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13597   SDLoc dl(Ld);
13598   EVT MemVT = Ld->getMemoryVT();
13599   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13600   unsigned RegSz = RegVT.getSizeInBits();
13601
13602   ISD::LoadExtType Ext = Ld->getExtensionType();
13603
13604   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13605          && "Only anyext and sext are currently implemented.");
13606   assert(MemVT != RegVT && "Cannot extend to the same type");
13607   assert(MemVT.isVector() && "Must load a vector from memory");
13608
13609   unsigned NumElems = RegVT.getVectorNumElements();
13610   unsigned MemSz = MemVT.getSizeInBits();
13611   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13612
13613   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13614     // The only way in which we have a legal 256-bit vector result but not the
13615     // integer 256-bit operations needed to directly lower a sextload is if we
13616     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13617     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13618     // correctly legalized. We do this late to allow the canonical form of
13619     // sextload to persist throughout the rest of the DAG combiner -- it wants
13620     // to fold together any extensions it can, and so will fuse a sign_extend
13621     // of an sextload into a sextload targeting a wider value.
13622     SDValue Load;
13623     if (MemSz == 128) {
13624       // Just switch this to a normal load.
13625       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13626                                        "it must be a legal 128-bit vector "
13627                                        "type!");
13628       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13629                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13630                   Ld->isInvariant(), Ld->getAlignment());
13631     } else {
13632       assert(MemSz < 128 &&
13633              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13634       // Do an sext load to a 128-bit vector type. We want to use the same
13635       // number of elements, but elements half as wide. This will end up being
13636       // recursively lowered by this routine, but will succeed as we definitely
13637       // have all the necessary features if we're using AVX1.
13638       EVT HalfEltVT =
13639           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13640       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13641       Load =
13642           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13643                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13644                          Ld->isNonTemporal(), Ld->isInvariant(),
13645                          Ld->getAlignment());
13646     }
13647
13648     // Replace chain users with the new chain.
13649     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13650     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13651
13652     // Finally, do a normal sign-extend to the desired register.
13653     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13654   }
13655
13656   // All sizes must be a power of two.
13657   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13658          "Non-power-of-two elements are not custom lowered!");
13659
13660   // Attempt to load the original value using scalar loads.
13661   // Find the largest scalar type that divides the total loaded size.
13662   MVT SclrLoadTy = MVT::i8;
13663   for (MVT Tp : MVT::integer_valuetypes()) {
13664     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13665       SclrLoadTy = Tp;
13666     }
13667   }
13668
13669   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13670   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13671       (64 <= MemSz))
13672     SclrLoadTy = MVT::f64;
13673
13674   // Calculate the number of scalar loads that we need to perform
13675   // in order to load our vector from memory.
13676   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13677
13678   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13679          "Can only lower sext loads with a single scalar load!");
13680
13681   unsigned loadRegZize = RegSz;
13682   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13683     loadRegZize /= 2;
13684
13685   // Represent our vector as a sequence of elements which are the
13686   // largest scalar that we can load.
13687   EVT LoadUnitVecVT = EVT::getVectorVT(
13688       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13689
13690   // Represent the data using the same element type that is stored in
13691   // memory. In practice, we ''widen'' MemVT.
13692   EVT WideVecVT =
13693       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13694                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13695
13696   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13697          "Invalid vector type");
13698
13699   // We can't shuffle using an illegal type.
13700   assert(TLI.isTypeLegal(WideVecVT) &&
13701          "We only lower types that form legal widened vector types");
13702
13703   SmallVector<SDValue, 8> Chains;
13704   SDValue Ptr = Ld->getBasePtr();
13705   SDValue Increment =
13706       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13707   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13708
13709   for (unsigned i = 0; i < NumLoads; ++i) {
13710     // Perform a single load.
13711     SDValue ScalarLoad =
13712         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13713                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13714                     Ld->getAlignment());
13715     Chains.push_back(ScalarLoad.getValue(1));
13716     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13717     // another round of DAGCombining.
13718     if (i == 0)
13719       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13720     else
13721       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13722                         ScalarLoad, DAG.getIntPtrConstant(i));
13723
13724     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13725   }
13726
13727   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13728
13729   // Bitcast the loaded value to a vector of the original element type, in
13730   // the size of the target vector type.
13731   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13732   unsigned SizeRatio = RegSz / MemSz;
13733
13734   if (Ext == ISD::SEXTLOAD) {
13735     // If we have SSE4.1, we can directly emit a VSEXT node.
13736     if (Subtarget->hasSSE41()) {
13737       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13738       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13739       return Sext;
13740     }
13741
13742     // Otherwise we'll shuffle the small elements in the high bits of the
13743     // larger type and perform an arithmetic shift. If the shift is not legal
13744     // it's better to scalarize.
13745     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13746            "We can't implement a sext load without an arithmetic right shift!");
13747
13748     // Redistribute the loaded elements into the different locations.
13749     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13750     for (unsigned i = 0; i != NumElems; ++i)
13751       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13752
13753     SDValue Shuff = DAG.getVectorShuffle(
13754         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13755
13756     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13757
13758     // Build the arithmetic shift.
13759     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13760                    MemVT.getVectorElementType().getSizeInBits();
13761     Shuff =
13762         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13763
13764     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13765     return Shuff;
13766   }
13767
13768   // Redistribute the loaded elements into the different locations.
13769   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13770   for (unsigned i = 0; i != NumElems; ++i)
13771     ShuffleVec[i * SizeRatio] = i;
13772
13773   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13774                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13775
13776   // Bitcast to the requested type.
13777   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13778   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13779   return Shuff;
13780 }
13781
13782 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13783 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13784 // from the AND / OR.
13785 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13786   Opc = Op.getOpcode();
13787   if (Opc != ISD::OR && Opc != ISD::AND)
13788     return false;
13789   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13790           Op.getOperand(0).hasOneUse() &&
13791           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13792           Op.getOperand(1).hasOneUse());
13793 }
13794
13795 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13796 // 1 and that the SETCC node has a single use.
13797 static bool isXor1OfSetCC(SDValue Op) {
13798   if (Op.getOpcode() != ISD::XOR)
13799     return false;
13800   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13801   if (N1C && N1C->getAPIntValue() == 1) {
13802     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13803       Op.getOperand(0).hasOneUse();
13804   }
13805   return false;
13806 }
13807
13808 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13809   bool addTest = true;
13810   SDValue Chain = Op.getOperand(0);
13811   SDValue Cond  = Op.getOperand(1);
13812   SDValue Dest  = Op.getOperand(2);
13813   SDLoc dl(Op);
13814   SDValue CC;
13815   bool Inverted = false;
13816
13817   if (Cond.getOpcode() == ISD::SETCC) {
13818     // Check for setcc([su]{add,sub,mul}o == 0).
13819     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13820         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13821         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13822         Cond.getOperand(0).getResNo() == 1 &&
13823         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13824          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13825          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13826          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13827          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13828          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13829       Inverted = true;
13830       Cond = Cond.getOperand(0);
13831     } else {
13832       SDValue NewCond = LowerSETCC(Cond, DAG);
13833       if (NewCond.getNode())
13834         Cond = NewCond;
13835     }
13836   }
13837 #if 0
13838   // FIXME: LowerXALUO doesn't handle these!!
13839   else if (Cond.getOpcode() == X86ISD::ADD  ||
13840            Cond.getOpcode() == X86ISD::SUB  ||
13841            Cond.getOpcode() == X86ISD::SMUL ||
13842            Cond.getOpcode() == X86ISD::UMUL)
13843     Cond = LowerXALUO(Cond, DAG);
13844 #endif
13845
13846   // Look pass (and (setcc_carry (cmp ...)), 1).
13847   if (Cond.getOpcode() == ISD::AND &&
13848       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13849     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13850     if (C && C->getAPIntValue() == 1)
13851       Cond = Cond.getOperand(0);
13852   }
13853
13854   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13855   // setting operand in place of the X86ISD::SETCC.
13856   unsigned CondOpcode = Cond.getOpcode();
13857   if (CondOpcode == X86ISD::SETCC ||
13858       CondOpcode == X86ISD::SETCC_CARRY) {
13859     CC = Cond.getOperand(0);
13860
13861     SDValue Cmp = Cond.getOperand(1);
13862     unsigned Opc = Cmp.getOpcode();
13863     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13864     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13865       Cond = Cmp;
13866       addTest = false;
13867     } else {
13868       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13869       default: break;
13870       case X86::COND_O:
13871       case X86::COND_B:
13872         // These can only come from an arithmetic instruction with overflow,
13873         // e.g. SADDO, UADDO.
13874         Cond = Cond.getNode()->getOperand(1);
13875         addTest = false;
13876         break;
13877       }
13878     }
13879   }
13880   CondOpcode = Cond.getOpcode();
13881   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13882       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13883       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13884        Cond.getOperand(0).getValueType() != MVT::i8)) {
13885     SDValue LHS = Cond.getOperand(0);
13886     SDValue RHS = Cond.getOperand(1);
13887     unsigned X86Opcode;
13888     unsigned X86Cond;
13889     SDVTList VTs;
13890     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13891     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13892     // X86ISD::INC).
13893     switch (CondOpcode) {
13894     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13895     case ISD::SADDO:
13896       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13897         if (C->isOne()) {
13898           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13899           break;
13900         }
13901       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13902     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13903     case ISD::SSUBO:
13904       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13905         if (C->isOne()) {
13906           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13907           break;
13908         }
13909       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13910     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13911     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13912     default: llvm_unreachable("unexpected overflowing operator");
13913     }
13914     if (Inverted)
13915       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13916     if (CondOpcode == ISD::UMULO)
13917       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13918                           MVT::i32);
13919     else
13920       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13921
13922     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13923
13924     if (CondOpcode == ISD::UMULO)
13925       Cond = X86Op.getValue(2);
13926     else
13927       Cond = X86Op.getValue(1);
13928
13929     CC = DAG.getConstant(X86Cond, MVT::i8);
13930     addTest = false;
13931   } else {
13932     unsigned CondOpc;
13933     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13934       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13935       if (CondOpc == ISD::OR) {
13936         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13937         // two branches instead of an explicit OR instruction with a
13938         // separate test.
13939         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13940             isX86LogicalCmp(Cmp)) {
13941           CC = Cond.getOperand(0).getOperand(0);
13942           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13943                               Chain, Dest, CC, Cmp);
13944           CC = Cond.getOperand(1).getOperand(0);
13945           Cond = Cmp;
13946           addTest = false;
13947         }
13948       } else { // ISD::AND
13949         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13950         // two branches instead of an explicit AND instruction with a
13951         // separate test. However, we only do this if this block doesn't
13952         // have a fall-through edge, because this requires an explicit
13953         // jmp when the condition is false.
13954         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13955             isX86LogicalCmp(Cmp) &&
13956             Op.getNode()->hasOneUse()) {
13957           X86::CondCode CCode =
13958             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13959           CCode = X86::GetOppositeBranchCondition(CCode);
13960           CC = DAG.getConstant(CCode, MVT::i8);
13961           SDNode *User = *Op.getNode()->use_begin();
13962           // Look for an unconditional branch following this conditional branch.
13963           // We need this because we need to reverse the successors in order
13964           // to implement FCMP_OEQ.
13965           if (User->getOpcode() == ISD::BR) {
13966             SDValue FalseBB = User->getOperand(1);
13967             SDNode *NewBR =
13968               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13969             assert(NewBR == User);
13970             (void)NewBR;
13971             Dest = FalseBB;
13972
13973             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13974                                 Chain, Dest, CC, Cmp);
13975             X86::CondCode CCode =
13976               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13977             CCode = X86::GetOppositeBranchCondition(CCode);
13978             CC = DAG.getConstant(CCode, MVT::i8);
13979             Cond = Cmp;
13980             addTest = false;
13981           }
13982         }
13983       }
13984     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13985       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13986       // It should be transformed during dag combiner except when the condition
13987       // is set by a arithmetics with overflow node.
13988       X86::CondCode CCode =
13989         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13990       CCode = X86::GetOppositeBranchCondition(CCode);
13991       CC = DAG.getConstant(CCode, MVT::i8);
13992       Cond = Cond.getOperand(0).getOperand(1);
13993       addTest = false;
13994     } else if (Cond.getOpcode() == ISD::SETCC &&
13995                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13996       // For FCMP_OEQ, we can emit
13997       // two branches instead of an explicit AND instruction with a
13998       // separate test. However, we only do this if this block doesn't
13999       // have a fall-through edge, because this requires an explicit
14000       // jmp when the condition is false.
14001       if (Op.getNode()->hasOneUse()) {
14002         SDNode *User = *Op.getNode()->use_begin();
14003         // Look for an unconditional branch following this conditional branch.
14004         // We need this because we need to reverse the successors in order
14005         // to implement FCMP_OEQ.
14006         if (User->getOpcode() == ISD::BR) {
14007           SDValue FalseBB = User->getOperand(1);
14008           SDNode *NewBR =
14009             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14010           assert(NewBR == User);
14011           (void)NewBR;
14012           Dest = FalseBB;
14013
14014           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14015                                     Cond.getOperand(0), Cond.getOperand(1));
14016           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14017           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14018           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14019                               Chain, Dest, CC, Cmp);
14020           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14021           Cond = Cmp;
14022           addTest = false;
14023         }
14024       }
14025     } else if (Cond.getOpcode() == ISD::SETCC &&
14026                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14027       // For FCMP_UNE, we can emit
14028       // two branches instead of an explicit AND instruction with a
14029       // separate test. However, we only do this if this block doesn't
14030       // have a fall-through edge, because this requires an explicit
14031       // jmp when the condition is false.
14032       if (Op.getNode()->hasOneUse()) {
14033         SDNode *User = *Op.getNode()->use_begin();
14034         // Look for an unconditional branch following this conditional branch.
14035         // We need this because we need to reverse the successors in order
14036         // to implement FCMP_UNE.
14037         if (User->getOpcode() == ISD::BR) {
14038           SDValue FalseBB = User->getOperand(1);
14039           SDNode *NewBR =
14040             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14041           assert(NewBR == User);
14042           (void)NewBR;
14043
14044           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14045                                     Cond.getOperand(0), Cond.getOperand(1));
14046           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14047           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14048           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14049                               Chain, Dest, CC, Cmp);
14050           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14051           Cond = Cmp;
14052           addTest = false;
14053           Dest = FalseBB;
14054         }
14055       }
14056     }
14057   }
14058
14059   if (addTest) {
14060     // Look pass the truncate if the high bits are known zero.
14061     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14062         Cond = Cond.getOperand(0);
14063
14064     // We know the result of AND is compared against zero. Try to match
14065     // it to BT.
14066     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14067       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14068       if (NewSetCC.getNode()) {
14069         CC = NewSetCC.getOperand(0);
14070         Cond = NewSetCC.getOperand(1);
14071         addTest = false;
14072       }
14073     }
14074   }
14075
14076   if (addTest) {
14077     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14078     CC = DAG.getConstant(X86Cond, MVT::i8);
14079     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14080   }
14081   Cond = ConvertCmpIfNecessary(Cond, DAG);
14082   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14083                      Chain, Dest, CC, Cond);
14084 }
14085
14086 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14087 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14088 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14089 // that the guard pages used by the OS virtual memory manager are allocated in
14090 // correct sequence.
14091 SDValue
14092 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14093                                            SelectionDAG &DAG) const {
14094   MachineFunction &MF = DAG.getMachineFunction();
14095   bool SplitStack = MF.shouldSplitStack();
14096   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14097                SplitStack;
14098   SDLoc dl(Op);
14099
14100   if (!Lower) {
14101     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14102     SDNode* Node = Op.getNode();
14103
14104     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14105     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14106         " not tell us which reg is the stack pointer!");
14107     EVT VT = Node->getValueType(0);
14108     SDValue Tmp1 = SDValue(Node, 0);
14109     SDValue Tmp2 = SDValue(Node, 1);
14110     SDValue Tmp3 = Node->getOperand(2);
14111     SDValue Chain = Tmp1.getOperand(0);
14112
14113     // Chain the dynamic stack allocation so that it doesn't modify the stack
14114     // pointer when other instructions are using the stack.
14115     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14116         SDLoc(Node));
14117
14118     SDValue Size = Tmp2.getOperand(1);
14119     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14120     Chain = SP.getValue(1);
14121     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14122     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14123     unsigned StackAlign = TFI.getStackAlignment();
14124     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14125     if (Align > StackAlign)
14126       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14127           DAG.getConstant(-(uint64_t)Align, VT));
14128     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14129
14130     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14131         DAG.getIntPtrConstant(0, true), SDValue(),
14132         SDLoc(Node));
14133
14134     SDValue Ops[2] = { Tmp1, Tmp2 };
14135     return DAG.getMergeValues(Ops, dl);
14136   }
14137
14138   // Get the inputs.
14139   SDValue Chain = Op.getOperand(0);
14140   SDValue Size  = Op.getOperand(1);
14141   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14142   EVT VT = Op.getNode()->getValueType(0);
14143
14144   bool Is64Bit = Subtarget->is64Bit();
14145   EVT SPTy = getPointerTy();
14146
14147   if (SplitStack) {
14148     MachineRegisterInfo &MRI = MF.getRegInfo();
14149
14150     if (Is64Bit) {
14151       // The 64 bit implementation of segmented stacks needs to clobber both r10
14152       // r11. This makes it impossible to use it along with nested parameters.
14153       const Function *F = MF.getFunction();
14154
14155       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14156            I != E; ++I)
14157         if (I->hasNestAttr())
14158           report_fatal_error("Cannot use segmented stacks with functions that "
14159                              "have nested arguments.");
14160     }
14161
14162     const TargetRegisterClass *AddrRegClass =
14163       getRegClassFor(getPointerTy());
14164     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14165     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14166     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14167                                 DAG.getRegister(Vreg, SPTy));
14168     SDValue Ops1[2] = { Value, Chain };
14169     return DAG.getMergeValues(Ops1, dl);
14170   } else {
14171     SDValue Flag;
14172     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14173
14174     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14175     Flag = Chain.getValue(1);
14176     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14177
14178     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14179
14180     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14181     unsigned SPReg = RegInfo->getStackRegister();
14182     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14183     Chain = SP.getValue(1);
14184
14185     if (Align) {
14186       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14187                        DAG.getConstant(-(uint64_t)Align, VT));
14188       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14189     }
14190
14191     SDValue Ops1[2] = { SP, Chain };
14192     return DAG.getMergeValues(Ops1, dl);
14193   }
14194 }
14195
14196 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14197   MachineFunction &MF = DAG.getMachineFunction();
14198   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14199
14200   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14201   SDLoc DL(Op);
14202
14203   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14204     // vastart just stores the address of the VarArgsFrameIndex slot into the
14205     // memory location argument.
14206     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14207                                    getPointerTy());
14208     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14209                         MachinePointerInfo(SV), false, false, 0);
14210   }
14211
14212   // __va_list_tag:
14213   //   gp_offset         (0 - 6 * 8)
14214   //   fp_offset         (48 - 48 + 8 * 16)
14215   //   overflow_arg_area (point to parameters coming in memory).
14216   //   reg_save_area
14217   SmallVector<SDValue, 8> MemOps;
14218   SDValue FIN = Op.getOperand(1);
14219   // Store gp_offset
14220   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14221                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14222                                                MVT::i32),
14223                                FIN, MachinePointerInfo(SV), false, false, 0);
14224   MemOps.push_back(Store);
14225
14226   // Store fp_offset
14227   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14228                     FIN, DAG.getIntPtrConstant(4));
14229   Store = DAG.getStore(Op.getOperand(0), DL,
14230                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14231                                        MVT::i32),
14232                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14233   MemOps.push_back(Store);
14234
14235   // Store ptr to overflow_arg_area
14236   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14237                     FIN, DAG.getIntPtrConstant(4));
14238   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14239                                     getPointerTy());
14240   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14241                        MachinePointerInfo(SV, 8),
14242                        false, false, 0);
14243   MemOps.push_back(Store);
14244
14245   // Store ptr to reg_save_area.
14246   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14247                     FIN, DAG.getIntPtrConstant(8));
14248   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14249                                     getPointerTy());
14250   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14251                        MachinePointerInfo(SV, 16), false, false, 0);
14252   MemOps.push_back(Store);
14253   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14254 }
14255
14256 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14257   assert(Subtarget->is64Bit() &&
14258          "LowerVAARG only handles 64-bit va_arg!");
14259   assert((Subtarget->isTargetLinux() ||
14260           Subtarget->isTargetDarwin()) &&
14261           "Unhandled target in LowerVAARG");
14262   assert(Op.getNode()->getNumOperands() == 4);
14263   SDValue Chain = Op.getOperand(0);
14264   SDValue SrcPtr = Op.getOperand(1);
14265   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14266   unsigned Align = Op.getConstantOperandVal(3);
14267   SDLoc dl(Op);
14268
14269   EVT ArgVT = Op.getNode()->getValueType(0);
14270   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14271   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14272   uint8_t ArgMode;
14273
14274   // Decide which area this value should be read from.
14275   // TODO: Implement the AMD64 ABI in its entirety. This simple
14276   // selection mechanism works only for the basic types.
14277   if (ArgVT == MVT::f80) {
14278     llvm_unreachable("va_arg for f80 not yet implemented");
14279   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14280     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14281   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14282     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14283   } else {
14284     llvm_unreachable("Unhandled argument type in LowerVAARG");
14285   }
14286
14287   if (ArgMode == 2) {
14288     // Sanity Check: Make sure using fp_offset makes sense.
14289     assert(!DAG.getTarget().Options.UseSoftFloat &&
14290            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14291                Attribute::NoImplicitFloat)) &&
14292            Subtarget->hasSSE1());
14293   }
14294
14295   // Insert VAARG_64 node into the DAG
14296   // VAARG_64 returns two values: Variable Argument Address, Chain
14297   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14298                        DAG.getConstant(ArgMode, MVT::i8),
14299                        DAG.getConstant(Align, MVT::i32)};
14300   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14301   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14302                                           VTs, InstOps, MVT::i64,
14303                                           MachinePointerInfo(SV),
14304                                           /*Align=*/0,
14305                                           /*Volatile=*/false,
14306                                           /*ReadMem=*/true,
14307                                           /*WriteMem=*/true);
14308   Chain = VAARG.getValue(1);
14309
14310   // Load the next argument and return it
14311   return DAG.getLoad(ArgVT, dl,
14312                      Chain,
14313                      VAARG,
14314                      MachinePointerInfo(),
14315                      false, false, false, 0);
14316 }
14317
14318 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14319                            SelectionDAG &DAG) {
14320   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14321   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14322   SDValue Chain = Op.getOperand(0);
14323   SDValue DstPtr = Op.getOperand(1);
14324   SDValue SrcPtr = Op.getOperand(2);
14325   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14326   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14327   SDLoc DL(Op);
14328
14329   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14330                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14331                        false,
14332                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14333 }
14334
14335 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14336 // amount is a constant. Takes immediate version of shift as input.
14337 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14338                                           SDValue SrcOp, uint64_t ShiftAmt,
14339                                           SelectionDAG &DAG) {
14340   MVT ElementType = VT.getVectorElementType();
14341
14342   // Fold this packed shift into its first operand if ShiftAmt is 0.
14343   if (ShiftAmt == 0)
14344     return SrcOp;
14345
14346   // Check for ShiftAmt >= element width
14347   if (ShiftAmt >= ElementType.getSizeInBits()) {
14348     if (Opc == X86ISD::VSRAI)
14349       ShiftAmt = ElementType.getSizeInBits() - 1;
14350     else
14351       return DAG.getConstant(0, VT);
14352   }
14353
14354   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14355          && "Unknown target vector shift-by-constant node");
14356
14357   // Fold this packed vector shift into a build vector if SrcOp is a
14358   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14359   if (VT == SrcOp.getSimpleValueType() &&
14360       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14361     SmallVector<SDValue, 8> Elts;
14362     unsigned NumElts = SrcOp->getNumOperands();
14363     ConstantSDNode *ND;
14364
14365     switch(Opc) {
14366     default: llvm_unreachable(nullptr);
14367     case X86ISD::VSHLI:
14368       for (unsigned i=0; i!=NumElts; ++i) {
14369         SDValue CurrentOp = SrcOp->getOperand(i);
14370         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14371           Elts.push_back(CurrentOp);
14372           continue;
14373         }
14374         ND = cast<ConstantSDNode>(CurrentOp);
14375         const APInt &C = ND->getAPIntValue();
14376         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14377       }
14378       break;
14379     case X86ISD::VSRLI:
14380       for (unsigned i=0; i!=NumElts; ++i) {
14381         SDValue CurrentOp = SrcOp->getOperand(i);
14382         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14383           Elts.push_back(CurrentOp);
14384           continue;
14385         }
14386         ND = cast<ConstantSDNode>(CurrentOp);
14387         const APInt &C = ND->getAPIntValue();
14388         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14389       }
14390       break;
14391     case X86ISD::VSRAI:
14392       for (unsigned i=0; i!=NumElts; ++i) {
14393         SDValue CurrentOp = SrcOp->getOperand(i);
14394         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14395           Elts.push_back(CurrentOp);
14396           continue;
14397         }
14398         ND = cast<ConstantSDNode>(CurrentOp);
14399         const APInt &C = ND->getAPIntValue();
14400         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14401       }
14402       break;
14403     }
14404
14405     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14406   }
14407
14408   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14409 }
14410
14411 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14412 // may or may not be a constant. Takes immediate version of shift as input.
14413 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14414                                    SDValue SrcOp, SDValue ShAmt,
14415                                    SelectionDAG &DAG) {
14416   MVT SVT = ShAmt.getSimpleValueType();
14417   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14418
14419   // Catch shift-by-constant.
14420   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14421     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14422                                       CShAmt->getZExtValue(), DAG);
14423
14424   // Change opcode to non-immediate version
14425   switch (Opc) {
14426     default: llvm_unreachable("Unknown target vector shift node");
14427     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14428     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14429     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14430   }
14431
14432   const X86Subtarget &Subtarget =
14433       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14434   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14435       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14436     // Let the shuffle legalizer expand this shift amount node.
14437     SDValue Op0 = ShAmt.getOperand(0);
14438     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14439     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14440   } else {
14441     // Need to build a vector containing shift amount.
14442     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14443     SmallVector<SDValue, 4> ShOps;
14444     ShOps.push_back(ShAmt);
14445     if (SVT == MVT::i32) {
14446       ShOps.push_back(DAG.getConstant(0, SVT));
14447       ShOps.push_back(DAG.getUNDEF(SVT));
14448     }
14449     ShOps.push_back(DAG.getUNDEF(SVT));
14450
14451     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14452     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14453   }
14454
14455   // The return type has to be a 128-bit type with the same element
14456   // type as the input type.
14457   MVT EltVT = VT.getVectorElementType();
14458   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14459
14460   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14461   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14462 }
14463
14464 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14465 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14466 /// necessary casting for \p Mask when lowering masking intrinsics.
14467 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14468                                     SDValue PreservedSrc,
14469                                     const X86Subtarget *Subtarget,
14470                                     SelectionDAG &DAG) {
14471     EVT VT = Op.getValueType();
14472     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14473                                   MVT::i1, VT.getVectorNumElements());
14474     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14475                                      Mask.getValueType().getSizeInBits());
14476     SDLoc dl(Op);
14477
14478     assert(MaskVT.isSimple() && "invalid mask type");
14479
14480     if (isAllOnes(Mask))
14481       return Op;
14482
14483     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14484     // are extracted by EXTRACT_SUBVECTOR.
14485     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14486                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14487                               DAG.getIntPtrConstant(0));
14488
14489     switch (Op.getOpcode()) {
14490       default: break;
14491       case X86ISD::PCMPEQM:
14492       case X86ISD::PCMPGTM:
14493       case X86ISD::CMPM:
14494       case X86ISD::CMPMU:
14495         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14496     }
14497     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14498       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14499     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14500 }
14501
14502 /// \brief Creates an SDNode for a predicated scalar operation.
14503 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14504 /// The mask is comming as MVT::i8 and it should be truncated
14505 /// to MVT::i1 while lowering masking intrinsics.
14506 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14507 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14508 /// a scalar instruction.
14509 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14510                                     SDValue PreservedSrc,
14511                                     const X86Subtarget *Subtarget,
14512                                     SelectionDAG &DAG) {
14513     if (isAllOnes(Mask))
14514       return Op;
14515
14516     EVT VT = Op.getValueType();
14517     SDLoc dl(Op);
14518     // The mask should be of type MVT::i1
14519     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14520
14521     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14522       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14523     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14524 }
14525
14526 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14527                                        SelectionDAG &DAG) {
14528   SDLoc dl(Op);
14529   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14530   EVT VT = Op.getValueType();
14531   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14532   if (IntrData) {
14533     switch(IntrData->Type) {
14534     case INTR_TYPE_1OP:
14535       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14536     case INTR_TYPE_2OP:
14537       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14538         Op.getOperand(2));
14539     case INTR_TYPE_3OP:
14540       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14541         Op.getOperand(2), Op.getOperand(3));
14542     case INTR_TYPE_1OP_MASK_RM: {
14543       SDValue Src = Op.getOperand(1);
14544       SDValue Src0 = Op.getOperand(2);
14545       SDValue Mask = Op.getOperand(3);
14546       SDValue RoundingMode = Op.getOperand(4);
14547       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14548                                               RoundingMode),
14549                                   Mask, Src0, Subtarget, DAG);
14550     }
14551     case INTR_TYPE_SCALAR_MASK_RM: {
14552       SDValue Src1 = Op.getOperand(1);
14553       SDValue Src2 = Op.getOperand(2);
14554       SDValue Src0 = Op.getOperand(3);
14555       SDValue Mask = Op.getOperand(4);
14556       // There are 2 kinds of intrinsics in this group:
14557       // (1) With supress-all-exceptions (sae) - 6 operands
14558       // (2) With rounding mode and sae - 7 operands.
14559       if (Op.getNumOperands() == 6) {
14560         SDValue Sae  = Op.getOperand(5);
14561         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14562                                                 Sae),
14563                                     Mask, Src0, Subtarget, DAG);
14564       }
14565       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14566       SDValue RoundingMode  = Op.getOperand(5);
14567       SDValue Sae  = Op.getOperand(6);
14568       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14569                                               RoundingMode, Sae),
14570                                   Mask, Src0, Subtarget, DAG);
14571     }
14572     case INTR_TYPE_2OP_MASK: {
14573       SDValue Src1 = Op.getOperand(1);
14574       SDValue Src2 = Op.getOperand(2);
14575       SDValue PassThru = Op.getOperand(3);
14576       SDValue Mask = Op.getOperand(4);
14577       // We specify 2 possible opcodes for intrinsics with rounding modes.
14578       // First, we check if the intrinsic may have non-default rounding mode,
14579       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14580       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14581       if (IntrWithRoundingModeOpcode != 0) {
14582         SDValue Rnd = Op.getOperand(5);
14583         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14584         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14585           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14586                                       dl, Op.getValueType(),
14587                                       Src1, Src2, Rnd),
14588                                       Mask, PassThru, Subtarget, DAG);
14589         }
14590       }
14591       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14592                                               Src1,Src2),
14593                                   Mask, PassThru, Subtarget, DAG);
14594     }
14595     case FMA_OP_MASK: {
14596       SDValue Src1 = Op.getOperand(1);
14597       SDValue Src2 = Op.getOperand(2);
14598       SDValue Src3 = Op.getOperand(3);
14599       SDValue Mask = Op.getOperand(4);
14600       // We specify 2 possible opcodes for intrinsics with rounding modes.
14601       // First, we check if the intrinsic may have non-default rounding mode,
14602       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14603       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14604       if (IntrWithRoundingModeOpcode != 0) {
14605         SDValue Rnd = Op.getOperand(5);
14606         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14607             X86::STATIC_ROUNDING::CUR_DIRECTION)
14608           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14609                                                   dl, Op.getValueType(),
14610                                                   Src1, Src2, Src3, Rnd),
14611                                       Mask, Src1, Subtarget, DAG);
14612       }
14613       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14614                                               dl, Op.getValueType(),
14615                                               Src1, Src2, Src3),
14616                                   Mask, Src1, Subtarget, DAG);
14617     }
14618     case CMP_MASK:
14619     case CMP_MASK_CC: {
14620       // Comparison intrinsics with masks.
14621       // Example of transformation:
14622       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14623       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14624       // (i8 (bitcast
14625       //   (v8i1 (insert_subvector undef,
14626       //           (v2i1 (and (PCMPEQM %a, %b),
14627       //                      (extract_subvector
14628       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14629       EVT VT = Op.getOperand(1).getValueType();
14630       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14631                                     VT.getVectorNumElements());
14632       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14633       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14634                                        Mask.getValueType().getSizeInBits());
14635       SDValue Cmp;
14636       if (IntrData->Type == CMP_MASK_CC) {
14637         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14638                     Op.getOperand(2), Op.getOperand(3));
14639       } else {
14640         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14641         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14642                     Op.getOperand(2));
14643       }
14644       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14645                                              DAG.getTargetConstant(0, MaskVT),
14646                                              Subtarget, DAG);
14647       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14648                                 DAG.getUNDEF(BitcastVT), CmpMask,
14649                                 DAG.getIntPtrConstant(0));
14650       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14651     }
14652     case COMI: { // Comparison intrinsics
14653       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14654       SDValue LHS = Op.getOperand(1);
14655       SDValue RHS = Op.getOperand(2);
14656       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14657       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14658       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14659       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14660                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14661       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14662     }
14663     case VSHIFT:
14664       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14665                                  Op.getOperand(1), Op.getOperand(2), DAG);
14666     case VSHIFT_MASK:
14667       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14668                                                       Op.getSimpleValueType(),
14669                                                       Op.getOperand(1),
14670                                                       Op.getOperand(2), DAG),
14671                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14672                                   DAG);
14673     case COMPRESS_EXPAND_IN_REG: {
14674       SDValue Mask = Op.getOperand(3);
14675       SDValue DataToCompress = Op.getOperand(1);
14676       SDValue PassThru = Op.getOperand(2);
14677       if (isAllOnes(Mask)) // return data as is
14678         return Op.getOperand(1);
14679       EVT VT = Op.getValueType();
14680       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14681                                     VT.getVectorNumElements());
14682       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14683                                        Mask.getValueType().getSizeInBits());
14684       SDLoc dl(Op);
14685       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14686                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14687                                   DAG.getIntPtrConstant(0));
14688
14689       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14690                          PassThru);
14691     }
14692     case BLEND: {
14693       SDValue Mask = Op.getOperand(3);
14694       EVT VT = Op.getValueType();
14695       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14696                                     VT.getVectorNumElements());
14697       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14698                                        Mask.getValueType().getSizeInBits());
14699       SDLoc dl(Op);
14700       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14701                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14702                                   DAG.getIntPtrConstant(0));
14703       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14704                          Op.getOperand(2));
14705     }
14706     default:
14707       break;
14708     }
14709   }
14710
14711   switch (IntNo) {
14712   default: return SDValue();    // Don't custom lower most intrinsics.
14713
14714   case Intrinsic::x86_avx2_permd:
14715   case Intrinsic::x86_avx2_permps:
14716     // Operands intentionally swapped. Mask is last operand to intrinsic,
14717     // but second operand for node/instruction.
14718     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14719                        Op.getOperand(2), Op.getOperand(1));
14720
14721   case Intrinsic::x86_avx512_mask_valign_q_512:
14722   case Intrinsic::x86_avx512_mask_valign_d_512:
14723     // Vector source operands are swapped.
14724     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14725                                             Op.getValueType(), Op.getOperand(2),
14726                                             Op.getOperand(1),
14727                                             Op.getOperand(3)),
14728                                 Op.getOperand(5), Op.getOperand(4),
14729                                 Subtarget, DAG);
14730
14731   // ptest and testp intrinsics. The intrinsic these come from are designed to
14732   // return an integer value, not just an instruction so lower it to the ptest
14733   // or testp pattern and a setcc for the result.
14734   case Intrinsic::x86_sse41_ptestz:
14735   case Intrinsic::x86_sse41_ptestc:
14736   case Intrinsic::x86_sse41_ptestnzc:
14737   case Intrinsic::x86_avx_ptestz_256:
14738   case Intrinsic::x86_avx_ptestc_256:
14739   case Intrinsic::x86_avx_ptestnzc_256:
14740   case Intrinsic::x86_avx_vtestz_ps:
14741   case Intrinsic::x86_avx_vtestc_ps:
14742   case Intrinsic::x86_avx_vtestnzc_ps:
14743   case Intrinsic::x86_avx_vtestz_pd:
14744   case Intrinsic::x86_avx_vtestc_pd:
14745   case Intrinsic::x86_avx_vtestnzc_pd:
14746   case Intrinsic::x86_avx_vtestz_ps_256:
14747   case Intrinsic::x86_avx_vtestc_ps_256:
14748   case Intrinsic::x86_avx_vtestnzc_ps_256:
14749   case Intrinsic::x86_avx_vtestz_pd_256:
14750   case Intrinsic::x86_avx_vtestc_pd_256:
14751   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14752     bool IsTestPacked = false;
14753     unsigned X86CC;
14754     switch (IntNo) {
14755     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14756     case Intrinsic::x86_avx_vtestz_ps:
14757     case Intrinsic::x86_avx_vtestz_pd:
14758     case Intrinsic::x86_avx_vtestz_ps_256:
14759     case Intrinsic::x86_avx_vtestz_pd_256:
14760       IsTestPacked = true; // Fallthrough
14761     case Intrinsic::x86_sse41_ptestz:
14762     case Intrinsic::x86_avx_ptestz_256:
14763       // ZF = 1
14764       X86CC = X86::COND_E;
14765       break;
14766     case Intrinsic::x86_avx_vtestc_ps:
14767     case Intrinsic::x86_avx_vtestc_pd:
14768     case Intrinsic::x86_avx_vtestc_ps_256:
14769     case Intrinsic::x86_avx_vtestc_pd_256:
14770       IsTestPacked = true; // Fallthrough
14771     case Intrinsic::x86_sse41_ptestc:
14772     case Intrinsic::x86_avx_ptestc_256:
14773       // CF = 1
14774       X86CC = X86::COND_B;
14775       break;
14776     case Intrinsic::x86_avx_vtestnzc_ps:
14777     case Intrinsic::x86_avx_vtestnzc_pd:
14778     case Intrinsic::x86_avx_vtestnzc_ps_256:
14779     case Intrinsic::x86_avx_vtestnzc_pd_256:
14780       IsTestPacked = true; // Fallthrough
14781     case Intrinsic::x86_sse41_ptestnzc:
14782     case Intrinsic::x86_avx_ptestnzc_256:
14783       // ZF and CF = 0
14784       X86CC = X86::COND_A;
14785       break;
14786     }
14787
14788     SDValue LHS = Op.getOperand(1);
14789     SDValue RHS = Op.getOperand(2);
14790     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14791     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14792     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14793     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14794     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14795   }
14796   case Intrinsic::x86_avx512_kortestz_w:
14797   case Intrinsic::x86_avx512_kortestc_w: {
14798     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14799     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14800     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14801     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14802     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14803     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14804     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14805   }
14806
14807   case Intrinsic::x86_sse42_pcmpistria128:
14808   case Intrinsic::x86_sse42_pcmpestria128:
14809   case Intrinsic::x86_sse42_pcmpistric128:
14810   case Intrinsic::x86_sse42_pcmpestric128:
14811   case Intrinsic::x86_sse42_pcmpistrio128:
14812   case Intrinsic::x86_sse42_pcmpestrio128:
14813   case Intrinsic::x86_sse42_pcmpistris128:
14814   case Intrinsic::x86_sse42_pcmpestris128:
14815   case Intrinsic::x86_sse42_pcmpistriz128:
14816   case Intrinsic::x86_sse42_pcmpestriz128: {
14817     unsigned Opcode;
14818     unsigned X86CC;
14819     switch (IntNo) {
14820     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14821     case Intrinsic::x86_sse42_pcmpistria128:
14822       Opcode = X86ISD::PCMPISTRI;
14823       X86CC = X86::COND_A;
14824       break;
14825     case Intrinsic::x86_sse42_pcmpestria128:
14826       Opcode = X86ISD::PCMPESTRI;
14827       X86CC = X86::COND_A;
14828       break;
14829     case Intrinsic::x86_sse42_pcmpistric128:
14830       Opcode = X86ISD::PCMPISTRI;
14831       X86CC = X86::COND_B;
14832       break;
14833     case Intrinsic::x86_sse42_pcmpestric128:
14834       Opcode = X86ISD::PCMPESTRI;
14835       X86CC = X86::COND_B;
14836       break;
14837     case Intrinsic::x86_sse42_pcmpistrio128:
14838       Opcode = X86ISD::PCMPISTRI;
14839       X86CC = X86::COND_O;
14840       break;
14841     case Intrinsic::x86_sse42_pcmpestrio128:
14842       Opcode = X86ISD::PCMPESTRI;
14843       X86CC = X86::COND_O;
14844       break;
14845     case Intrinsic::x86_sse42_pcmpistris128:
14846       Opcode = X86ISD::PCMPISTRI;
14847       X86CC = X86::COND_S;
14848       break;
14849     case Intrinsic::x86_sse42_pcmpestris128:
14850       Opcode = X86ISD::PCMPESTRI;
14851       X86CC = X86::COND_S;
14852       break;
14853     case Intrinsic::x86_sse42_pcmpistriz128:
14854       Opcode = X86ISD::PCMPISTRI;
14855       X86CC = X86::COND_E;
14856       break;
14857     case Intrinsic::x86_sse42_pcmpestriz128:
14858       Opcode = X86ISD::PCMPESTRI;
14859       X86CC = X86::COND_E;
14860       break;
14861     }
14862     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14863     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14864     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14865     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14866                                 DAG.getConstant(X86CC, MVT::i8),
14867                                 SDValue(PCMP.getNode(), 1));
14868     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14869   }
14870
14871   case Intrinsic::x86_sse42_pcmpistri128:
14872   case Intrinsic::x86_sse42_pcmpestri128: {
14873     unsigned Opcode;
14874     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14875       Opcode = X86ISD::PCMPISTRI;
14876     else
14877       Opcode = X86ISD::PCMPESTRI;
14878
14879     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14880     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14881     return DAG.getNode(Opcode, dl, VTs, NewOps);
14882   }
14883   }
14884 }
14885
14886 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14887                               SDValue Src, SDValue Mask, SDValue Base,
14888                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14889                               const X86Subtarget * Subtarget) {
14890   SDLoc dl(Op);
14891   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14892   assert(C && "Invalid scale type");
14893   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14894   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14895                              Index.getSimpleValueType().getVectorNumElements());
14896   SDValue MaskInReg;
14897   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14898   if (MaskC)
14899     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14900   else
14901     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14902   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14903   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14904   SDValue Segment = DAG.getRegister(0, MVT::i32);
14905   if (Src.getOpcode() == ISD::UNDEF)
14906     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14907   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14908   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14909   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14910   return DAG.getMergeValues(RetOps, dl);
14911 }
14912
14913 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14914                                SDValue Src, SDValue Mask, SDValue Base,
14915                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14916   SDLoc dl(Op);
14917   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14918   assert(C && "Invalid scale type");
14919   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14920   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14921   SDValue Segment = DAG.getRegister(0, MVT::i32);
14922   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14923                              Index.getSimpleValueType().getVectorNumElements());
14924   SDValue MaskInReg;
14925   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14926   if (MaskC)
14927     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14928   else
14929     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14930   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14931   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14932   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14933   return SDValue(Res, 1);
14934 }
14935
14936 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14937                                SDValue Mask, SDValue Base, SDValue Index,
14938                                SDValue ScaleOp, SDValue Chain) {
14939   SDLoc dl(Op);
14940   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14941   assert(C && "Invalid scale type");
14942   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14943   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14944   SDValue Segment = DAG.getRegister(0, MVT::i32);
14945   EVT MaskVT =
14946     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14947   SDValue MaskInReg;
14948   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14949   if (MaskC)
14950     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14951   else
14952     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14953   //SDVTList VTs = DAG.getVTList(MVT::Other);
14954   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14955   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14956   return SDValue(Res, 0);
14957 }
14958
14959 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14960 // read performance monitor counters (x86_rdpmc).
14961 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14962                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14963                               SmallVectorImpl<SDValue> &Results) {
14964   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14965   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14966   SDValue LO, HI;
14967
14968   // The ECX register is used to select the index of the performance counter
14969   // to read.
14970   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14971                                    N->getOperand(2));
14972   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14973
14974   // Reads the content of a 64-bit performance counter and returns it in the
14975   // registers EDX:EAX.
14976   if (Subtarget->is64Bit()) {
14977     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14978     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14979                             LO.getValue(2));
14980   } else {
14981     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14982     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14983                             LO.getValue(2));
14984   }
14985   Chain = HI.getValue(1);
14986
14987   if (Subtarget->is64Bit()) {
14988     // The EAX register is loaded with the low-order 32 bits. The EDX register
14989     // is loaded with the supported high-order bits of the counter.
14990     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14991                               DAG.getConstant(32, MVT::i8));
14992     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14993     Results.push_back(Chain);
14994     return;
14995   }
14996
14997   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14998   SDValue Ops[] = { LO, HI };
14999   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15000   Results.push_back(Pair);
15001   Results.push_back(Chain);
15002 }
15003
15004 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15005 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15006 // also used to custom lower READCYCLECOUNTER nodes.
15007 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15008                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15009                               SmallVectorImpl<SDValue> &Results) {
15010   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15011   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15012   SDValue LO, HI;
15013
15014   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15015   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15016   // and the EAX register is loaded with the low-order 32 bits.
15017   if (Subtarget->is64Bit()) {
15018     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15019     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15020                             LO.getValue(2));
15021   } else {
15022     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15023     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15024                             LO.getValue(2));
15025   }
15026   SDValue Chain = HI.getValue(1);
15027
15028   if (Opcode == X86ISD::RDTSCP_DAG) {
15029     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15030
15031     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15032     // the ECX register. Add 'ecx' explicitly to the chain.
15033     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15034                                      HI.getValue(2));
15035     // Explicitly store the content of ECX at the location passed in input
15036     // to the 'rdtscp' intrinsic.
15037     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15038                          MachinePointerInfo(), false, false, 0);
15039   }
15040
15041   if (Subtarget->is64Bit()) {
15042     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15043     // the EAX register is loaded with the low-order 32 bits.
15044     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15045                               DAG.getConstant(32, MVT::i8));
15046     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15047     Results.push_back(Chain);
15048     return;
15049   }
15050
15051   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15052   SDValue Ops[] = { LO, HI };
15053   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15054   Results.push_back(Pair);
15055   Results.push_back(Chain);
15056 }
15057
15058 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15059                                      SelectionDAG &DAG) {
15060   SmallVector<SDValue, 2> Results;
15061   SDLoc DL(Op);
15062   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15063                           Results);
15064   return DAG.getMergeValues(Results, DL);
15065 }
15066
15067
15068 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15069                                       SelectionDAG &DAG) {
15070   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15071
15072   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15073   if (!IntrData)
15074     return SDValue();
15075
15076   SDLoc dl(Op);
15077   switch(IntrData->Type) {
15078   default:
15079     llvm_unreachable("Unknown Intrinsic Type");
15080     break;
15081   case RDSEED:
15082   case RDRAND: {
15083     // Emit the node with the right value type.
15084     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15085     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15086
15087     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15088     // Otherwise return the value from Rand, which is always 0, casted to i32.
15089     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15090                       DAG.getConstant(1, Op->getValueType(1)),
15091                       DAG.getConstant(X86::COND_B, MVT::i32),
15092                       SDValue(Result.getNode(), 1) };
15093     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15094                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15095                                   Ops);
15096
15097     // Return { result, isValid, chain }.
15098     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15099                        SDValue(Result.getNode(), 2));
15100   }
15101   case GATHER: {
15102   //gather(v1, mask, index, base, scale);
15103     SDValue Chain = Op.getOperand(0);
15104     SDValue Src   = Op.getOperand(2);
15105     SDValue Base  = Op.getOperand(3);
15106     SDValue Index = Op.getOperand(4);
15107     SDValue Mask  = Op.getOperand(5);
15108     SDValue Scale = Op.getOperand(6);
15109     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15110                           Subtarget);
15111   }
15112   case SCATTER: {
15113   //scatter(base, mask, index, v1, scale);
15114     SDValue Chain = Op.getOperand(0);
15115     SDValue Base  = Op.getOperand(2);
15116     SDValue Mask  = Op.getOperand(3);
15117     SDValue Index = Op.getOperand(4);
15118     SDValue Src   = Op.getOperand(5);
15119     SDValue Scale = Op.getOperand(6);
15120     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15121   }
15122   case PREFETCH: {
15123     SDValue Hint = Op.getOperand(6);
15124     unsigned HintVal;
15125     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15126         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15127       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15128     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15129     SDValue Chain = Op.getOperand(0);
15130     SDValue Mask  = Op.getOperand(2);
15131     SDValue Index = Op.getOperand(3);
15132     SDValue Base  = Op.getOperand(4);
15133     SDValue Scale = Op.getOperand(5);
15134     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15135   }
15136   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15137   case RDTSC: {
15138     SmallVector<SDValue, 2> Results;
15139     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15140     return DAG.getMergeValues(Results, dl);
15141   }
15142   // Read Performance Monitoring Counters.
15143   case RDPMC: {
15144     SmallVector<SDValue, 2> Results;
15145     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15146     return DAG.getMergeValues(Results, dl);
15147   }
15148   // XTEST intrinsics.
15149   case XTEST: {
15150     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15151     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15152     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15153                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15154                                 InTrans);
15155     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15156     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15157                        Ret, SDValue(InTrans.getNode(), 1));
15158   }
15159   // ADC/ADCX/SBB
15160   case ADX: {
15161     SmallVector<SDValue, 2> Results;
15162     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15163     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15164     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15165                                 DAG.getConstant(-1, MVT::i8));
15166     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15167                               Op.getOperand(4), GenCF.getValue(1));
15168     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15169                                  Op.getOperand(5), MachinePointerInfo(),
15170                                  false, false, 0);
15171     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15172                                 DAG.getConstant(X86::COND_B, MVT::i8),
15173                                 Res.getValue(1));
15174     Results.push_back(SetCC);
15175     Results.push_back(Store);
15176     return DAG.getMergeValues(Results, dl);
15177   }
15178   case COMPRESS_TO_MEM: {
15179     SDLoc dl(Op);
15180     SDValue Mask = Op.getOperand(4);
15181     SDValue DataToCompress = Op.getOperand(3);
15182     SDValue Addr = Op.getOperand(2);
15183     SDValue Chain = Op.getOperand(0);
15184
15185     if (isAllOnes(Mask)) // return just a store
15186       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15187                           MachinePointerInfo(), false, false, 0);
15188
15189     EVT VT = DataToCompress.getValueType();
15190     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15191                                   VT.getVectorNumElements());
15192     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15193                                      Mask.getValueType().getSizeInBits());
15194     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15195                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15196                                 DAG.getIntPtrConstant(0));
15197
15198     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15199                                       DataToCompress, DAG.getUNDEF(VT));
15200     return DAG.getStore(Chain, dl, Compressed, Addr,
15201                         MachinePointerInfo(), false, false, 0);
15202   }
15203   case EXPAND_FROM_MEM: {
15204     SDLoc dl(Op);
15205     SDValue Mask = Op.getOperand(4);
15206     SDValue PathThru = Op.getOperand(3);
15207     SDValue Addr = Op.getOperand(2);
15208     SDValue Chain = Op.getOperand(0);
15209     EVT VT = Op.getValueType();
15210
15211     if (isAllOnes(Mask)) // return just a load
15212       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15213                          false, 0);
15214     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15215                                   VT.getVectorNumElements());
15216     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15217                                      Mask.getValueType().getSizeInBits());
15218     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15219                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15220                                 DAG.getIntPtrConstant(0));
15221
15222     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15223                                    false, false, false, 0);
15224
15225     SDValue Results[] = {
15226         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15227         Chain};
15228     return DAG.getMergeValues(Results, dl);
15229   }
15230   }
15231 }
15232
15233 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15234                                            SelectionDAG &DAG) const {
15235   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15236   MFI->setReturnAddressIsTaken(true);
15237
15238   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15239     return SDValue();
15240
15241   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15242   SDLoc dl(Op);
15243   EVT PtrVT = getPointerTy();
15244
15245   if (Depth > 0) {
15246     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15247     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15248     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15249     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15250                        DAG.getNode(ISD::ADD, dl, PtrVT,
15251                                    FrameAddr, Offset),
15252                        MachinePointerInfo(), false, false, false, 0);
15253   }
15254
15255   // Just load the return address.
15256   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15257   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15258                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15259 }
15260
15261 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15262   MachineFunction &MF = DAG.getMachineFunction();
15263   MachineFrameInfo *MFI = MF.getFrameInfo();
15264   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15265   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15266   EVT VT = Op.getValueType();
15267
15268   MFI->setFrameAddressIsTaken(true);
15269
15270   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15271     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15272     // is not possible to crawl up the stack without looking at the unwind codes
15273     // simultaneously.
15274     int FrameAddrIndex = FuncInfo->getFAIndex();
15275     if (!FrameAddrIndex) {
15276       // Set up a frame object for the return address.
15277       unsigned SlotSize = RegInfo->getSlotSize();
15278       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15279           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15280       FuncInfo->setFAIndex(FrameAddrIndex);
15281     }
15282     return DAG.getFrameIndex(FrameAddrIndex, VT);
15283   }
15284
15285   unsigned FrameReg =
15286       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15287   SDLoc dl(Op);  // FIXME probably not meaningful
15288   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15289   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15290           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15291          "Invalid Frame Register!");
15292   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15293   while (Depth--)
15294     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15295                             MachinePointerInfo(),
15296                             false, false, false, 0);
15297   return FrameAddr;
15298 }
15299
15300 // FIXME? Maybe this could be a TableGen attribute on some registers and
15301 // this table could be generated automatically from RegInfo.
15302 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15303                                               EVT VT) const {
15304   unsigned Reg = StringSwitch<unsigned>(RegName)
15305                        .Case("esp", X86::ESP)
15306                        .Case("rsp", X86::RSP)
15307                        .Default(0);
15308   if (Reg)
15309     return Reg;
15310   report_fatal_error("Invalid register name global variable");
15311 }
15312
15313 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15314                                                      SelectionDAG &DAG) const {
15315   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15316   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15317 }
15318
15319 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15320   SDValue Chain     = Op.getOperand(0);
15321   SDValue Offset    = Op.getOperand(1);
15322   SDValue Handler   = Op.getOperand(2);
15323   SDLoc dl      (Op);
15324
15325   EVT PtrVT = getPointerTy();
15326   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15327   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15328   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15329           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15330          "Invalid Frame Register!");
15331   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15332   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15333
15334   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15335                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15336   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15337   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15338                        false, false, 0);
15339   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15340
15341   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15342                      DAG.getRegister(StoreAddrReg, PtrVT));
15343 }
15344
15345 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15346                                                SelectionDAG &DAG) const {
15347   SDLoc DL(Op);
15348   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15349                      DAG.getVTList(MVT::i32, MVT::Other),
15350                      Op.getOperand(0), Op.getOperand(1));
15351 }
15352
15353 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15354                                                 SelectionDAG &DAG) const {
15355   SDLoc DL(Op);
15356   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15357                      Op.getOperand(0), Op.getOperand(1));
15358 }
15359
15360 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15361   return Op.getOperand(0);
15362 }
15363
15364 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15365                                                 SelectionDAG &DAG) const {
15366   SDValue Root = Op.getOperand(0);
15367   SDValue Trmp = Op.getOperand(1); // trampoline
15368   SDValue FPtr = Op.getOperand(2); // nested function
15369   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15370   SDLoc dl (Op);
15371
15372   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15373   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15374
15375   if (Subtarget->is64Bit()) {
15376     SDValue OutChains[6];
15377
15378     // Large code-model.
15379     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15380     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15381
15382     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15383     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15384
15385     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15386
15387     // Load the pointer to the nested function into R11.
15388     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15389     SDValue Addr = Trmp;
15390     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15391                                 Addr, MachinePointerInfo(TrmpAddr),
15392                                 false, false, 0);
15393
15394     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15395                        DAG.getConstant(2, MVT::i64));
15396     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15397                                 MachinePointerInfo(TrmpAddr, 2),
15398                                 false, false, 2);
15399
15400     // Load the 'nest' parameter value into R10.
15401     // R10 is specified in X86CallingConv.td
15402     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15403     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15404                        DAG.getConstant(10, MVT::i64));
15405     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15406                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15407                                 false, false, 0);
15408
15409     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15410                        DAG.getConstant(12, MVT::i64));
15411     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15412                                 MachinePointerInfo(TrmpAddr, 12),
15413                                 false, false, 2);
15414
15415     // Jump to the nested function.
15416     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15417     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15418                        DAG.getConstant(20, MVT::i64));
15419     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15420                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15421                                 false, false, 0);
15422
15423     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15424     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15425                        DAG.getConstant(22, MVT::i64));
15426     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15427                                 MachinePointerInfo(TrmpAddr, 22),
15428                                 false, false, 0);
15429
15430     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15431   } else {
15432     const Function *Func =
15433       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15434     CallingConv::ID CC = Func->getCallingConv();
15435     unsigned NestReg;
15436
15437     switch (CC) {
15438     default:
15439       llvm_unreachable("Unsupported calling convention");
15440     case CallingConv::C:
15441     case CallingConv::X86_StdCall: {
15442       // Pass 'nest' parameter in ECX.
15443       // Must be kept in sync with X86CallingConv.td
15444       NestReg = X86::ECX;
15445
15446       // Check that ECX wasn't needed by an 'inreg' parameter.
15447       FunctionType *FTy = Func->getFunctionType();
15448       const AttributeSet &Attrs = Func->getAttributes();
15449
15450       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15451         unsigned InRegCount = 0;
15452         unsigned Idx = 1;
15453
15454         for (FunctionType::param_iterator I = FTy->param_begin(),
15455              E = FTy->param_end(); I != E; ++I, ++Idx)
15456           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15457             // FIXME: should only count parameters that are lowered to integers.
15458             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15459
15460         if (InRegCount > 2) {
15461           report_fatal_error("Nest register in use - reduce number of inreg"
15462                              " parameters!");
15463         }
15464       }
15465       break;
15466     }
15467     case CallingConv::X86_FastCall:
15468     case CallingConv::X86_ThisCall:
15469     case CallingConv::Fast:
15470       // Pass 'nest' parameter in EAX.
15471       // Must be kept in sync with X86CallingConv.td
15472       NestReg = X86::EAX;
15473       break;
15474     }
15475
15476     SDValue OutChains[4];
15477     SDValue Addr, Disp;
15478
15479     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15480                        DAG.getConstant(10, MVT::i32));
15481     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15482
15483     // This is storing the opcode for MOV32ri.
15484     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15485     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15486     OutChains[0] = DAG.getStore(Root, dl,
15487                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15488                                 Trmp, MachinePointerInfo(TrmpAddr),
15489                                 false, false, 0);
15490
15491     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15492                        DAG.getConstant(1, MVT::i32));
15493     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15494                                 MachinePointerInfo(TrmpAddr, 1),
15495                                 false, false, 1);
15496
15497     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15498     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15499                        DAG.getConstant(5, MVT::i32));
15500     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15501                                 MachinePointerInfo(TrmpAddr, 5),
15502                                 false, false, 1);
15503
15504     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15505                        DAG.getConstant(6, MVT::i32));
15506     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15507                                 MachinePointerInfo(TrmpAddr, 6),
15508                                 false, false, 1);
15509
15510     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15511   }
15512 }
15513
15514 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15515                                             SelectionDAG &DAG) const {
15516   /*
15517    The rounding mode is in bits 11:10 of FPSR, and has the following
15518    settings:
15519      00 Round to nearest
15520      01 Round to -inf
15521      10 Round to +inf
15522      11 Round to 0
15523
15524   FLT_ROUNDS, on the other hand, expects the following:
15525     -1 Undefined
15526      0 Round to 0
15527      1 Round to nearest
15528      2 Round to +inf
15529      3 Round to -inf
15530
15531   To perform the conversion, we do:
15532     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15533   */
15534
15535   MachineFunction &MF = DAG.getMachineFunction();
15536   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15537   unsigned StackAlignment = TFI.getStackAlignment();
15538   MVT VT = Op.getSimpleValueType();
15539   SDLoc DL(Op);
15540
15541   // Save FP Control Word to stack slot
15542   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15543   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15544
15545   MachineMemOperand *MMO =
15546    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15547                            MachineMemOperand::MOStore, 2, 2);
15548
15549   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15550   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15551                                           DAG.getVTList(MVT::Other),
15552                                           Ops, MVT::i16, MMO);
15553
15554   // Load FP Control Word from stack slot
15555   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15556                             MachinePointerInfo(), false, false, false, 0);
15557
15558   // Transform as necessary
15559   SDValue CWD1 =
15560     DAG.getNode(ISD::SRL, DL, MVT::i16,
15561                 DAG.getNode(ISD::AND, DL, MVT::i16,
15562                             CWD, DAG.getConstant(0x800, MVT::i16)),
15563                 DAG.getConstant(11, MVT::i8));
15564   SDValue CWD2 =
15565     DAG.getNode(ISD::SRL, DL, MVT::i16,
15566                 DAG.getNode(ISD::AND, DL, MVT::i16,
15567                             CWD, DAG.getConstant(0x400, MVT::i16)),
15568                 DAG.getConstant(9, MVT::i8));
15569
15570   SDValue RetVal =
15571     DAG.getNode(ISD::AND, DL, MVT::i16,
15572                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15573                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15574                             DAG.getConstant(1, MVT::i16)),
15575                 DAG.getConstant(3, MVT::i16));
15576
15577   return DAG.getNode((VT.getSizeInBits() < 16 ?
15578                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15579 }
15580
15581 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15582   MVT VT = Op.getSimpleValueType();
15583   EVT OpVT = VT;
15584   unsigned NumBits = VT.getSizeInBits();
15585   SDLoc dl(Op);
15586
15587   Op = Op.getOperand(0);
15588   if (VT == MVT::i8) {
15589     // Zero extend to i32 since there is not an i8 bsr.
15590     OpVT = MVT::i32;
15591     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15592   }
15593
15594   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15595   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15596   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15597
15598   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15599   SDValue Ops[] = {
15600     Op,
15601     DAG.getConstant(NumBits+NumBits-1, OpVT),
15602     DAG.getConstant(X86::COND_E, MVT::i8),
15603     Op.getValue(1)
15604   };
15605   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15606
15607   // Finally xor with NumBits-1.
15608   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15609
15610   if (VT == MVT::i8)
15611     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15612   return Op;
15613 }
15614
15615 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15616   MVT VT = Op.getSimpleValueType();
15617   EVT OpVT = VT;
15618   unsigned NumBits = VT.getSizeInBits();
15619   SDLoc dl(Op);
15620
15621   Op = Op.getOperand(0);
15622   if (VT == MVT::i8) {
15623     // Zero extend to i32 since there is not an i8 bsr.
15624     OpVT = MVT::i32;
15625     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15626   }
15627
15628   // Issue a bsr (scan bits in reverse).
15629   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15630   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15631
15632   // And xor with NumBits-1.
15633   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15634
15635   if (VT == MVT::i8)
15636     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15637   return Op;
15638 }
15639
15640 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15641   MVT VT = Op.getSimpleValueType();
15642   unsigned NumBits = VT.getSizeInBits();
15643   SDLoc dl(Op);
15644   Op = Op.getOperand(0);
15645
15646   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15647   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15648   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15649
15650   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15651   SDValue Ops[] = {
15652     Op,
15653     DAG.getConstant(NumBits, VT),
15654     DAG.getConstant(X86::COND_E, MVT::i8),
15655     Op.getValue(1)
15656   };
15657   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15658 }
15659
15660 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15661 // ones, and then concatenate the result back.
15662 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15663   MVT VT = Op.getSimpleValueType();
15664
15665   assert(VT.is256BitVector() && VT.isInteger() &&
15666          "Unsupported value type for operation");
15667
15668   unsigned NumElems = VT.getVectorNumElements();
15669   SDLoc dl(Op);
15670
15671   // Extract the LHS vectors
15672   SDValue LHS = Op.getOperand(0);
15673   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15674   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15675
15676   // Extract the RHS vectors
15677   SDValue RHS = Op.getOperand(1);
15678   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15679   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15680
15681   MVT EltVT = VT.getVectorElementType();
15682   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15683
15684   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15685                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15686                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15687 }
15688
15689 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15690   assert(Op.getSimpleValueType().is256BitVector() &&
15691          Op.getSimpleValueType().isInteger() &&
15692          "Only handle AVX 256-bit vector integer operation");
15693   return Lower256IntArith(Op, DAG);
15694 }
15695
15696 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15697   assert(Op.getSimpleValueType().is256BitVector() &&
15698          Op.getSimpleValueType().isInteger() &&
15699          "Only handle AVX 256-bit vector integer operation");
15700   return Lower256IntArith(Op, DAG);
15701 }
15702
15703 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15704                         SelectionDAG &DAG) {
15705   SDLoc dl(Op);
15706   MVT VT = Op.getSimpleValueType();
15707
15708   // Decompose 256-bit ops into smaller 128-bit ops.
15709   if (VT.is256BitVector() && !Subtarget->hasInt256())
15710     return Lower256IntArith(Op, DAG);
15711
15712   SDValue A = Op.getOperand(0);
15713   SDValue B = Op.getOperand(1);
15714
15715   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15716   if (VT == MVT::v4i32) {
15717     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15718            "Should not custom lower when pmuldq is available!");
15719
15720     // Extract the odd parts.
15721     static const int UnpackMask[] = { 1, -1, 3, -1 };
15722     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15723     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15724
15725     // Multiply the even parts.
15726     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15727     // Now multiply odd parts.
15728     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15729
15730     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15731     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15732
15733     // Merge the two vectors back together with a shuffle. This expands into 2
15734     // shuffles.
15735     static const int ShufMask[] = { 0, 4, 2, 6 };
15736     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15737   }
15738
15739   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15740          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15741
15742   //  Ahi = psrlqi(a, 32);
15743   //  Bhi = psrlqi(b, 32);
15744   //
15745   //  AloBlo = pmuludq(a, b);
15746   //  AloBhi = pmuludq(a, Bhi);
15747   //  AhiBlo = pmuludq(Ahi, b);
15748
15749   //  AloBhi = psllqi(AloBhi, 32);
15750   //  AhiBlo = psllqi(AhiBlo, 32);
15751   //  return AloBlo + AloBhi + AhiBlo;
15752
15753   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15754   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15755
15756   // Bit cast to 32-bit vectors for MULUDQ
15757   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15758                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15759   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15760   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15761   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15762   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15763
15764   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15765   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15766   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15767
15768   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15769   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15770
15771   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15772   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15773 }
15774
15775 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15776   assert(Subtarget->isTargetWin64() && "Unexpected target");
15777   EVT VT = Op.getValueType();
15778   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15779          "Unexpected return type for lowering");
15780
15781   RTLIB::Libcall LC;
15782   bool isSigned;
15783   switch (Op->getOpcode()) {
15784   default: llvm_unreachable("Unexpected request for libcall!");
15785   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15786   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15787   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15788   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15789   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15790   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15791   }
15792
15793   SDLoc dl(Op);
15794   SDValue InChain = DAG.getEntryNode();
15795
15796   TargetLowering::ArgListTy Args;
15797   TargetLowering::ArgListEntry Entry;
15798   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15799     EVT ArgVT = Op->getOperand(i).getValueType();
15800     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15801            "Unexpected argument type for lowering");
15802     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15803     Entry.Node = StackPtr;
15804     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15805                            false, false, 16);
15806     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15807     Entry.Ty = PointerType::get(ArgTy,0);
15808     Entry.isSExt = false;
15809     Entry.isZExt = false;
15810     Args.push_back(Entry);
15811   }
15812
15813   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15814                                          getPointerTy());
15815
15816   TargetLowering::CallLoweringInfo CLI(DAG);
15817   CLI.setDebugLoc(dl).setChain(InChain)
15818     .setCallee(getLibcallCallingConv(LC),
15819                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15820                Callee, std::move(Args), 0)
15821     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15822
15823   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15824   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15825 }
15826
15827 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15828                              SelectionDAG &DAG) {
15829   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15830   EVT VT = Op0.getValueType();
15831   SDLoc dl(Op);
15832
15833   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15834          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15835
15836   // PMULxD operations multiply each even value (starting at 0) of LHS with
15837   // the related value of RHS and produce a widen result.
15838   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15839   // => <2 x i64> <ae|cg>
15840   //
15841   // In other word, to have all the results, we need to perform two PMULxD:
15842   // 1. one with the even values.
15843   // 2. one with the odd values.
15844   // To achieve #2, with need to place the odd values at an even position.
15845   //
15846   // Place the odd value at an even position (basically, shift all values 1
15847   // step to the left):
15848   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15849   // <a|b|c|d> => <b|undef|d|undef>
15850   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15851   // <e|f|g|h> => <f|undef|h|undef>
15852   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15853
15854   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15855   // ints.
15856   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15857   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15858   unsigned Opcode =
15859       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15860   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15861   // => <2 x i64> <ae|cg>
15862   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15863                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15864   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15865   // => <2 x i64> <bf|dh>
15866   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15867                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15868
15869   // Shuffle it back into the right order.
15870   SDValue Highs, Lows;
15871   if (VT == MVT::v8i32) {
15872     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15873     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15874     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15875     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15876   } else {
15877     const int HighMask[] = {1, 5, 3, 7};
15878     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15879     const int LowMask[] = {0, 4, 2, 6};
15880     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15881   }
15882
15883   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15884   // unsigned multiply.
15885   if (IsSigned && !Subtarget->hasSSE41()) {
15886     SDValue ShAmt =
15887         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15888     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15889                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15890     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15891                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15892
15893     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15894     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15895   }
15896
15897   // The first result of MUL_LOHI is actually the low value, followed by the
15898   // high value.
15899   SDValue Ops[] = {Lows, Highs};
15900   return DAG.getMergeValues(Ops, dl);
15901 }
15902
15903 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15904                                          const X86Subtarget *Subtarget) {
15905   MVT VT = Op.getSimpleValueType();
15906   SDLoc dl(Op);
15907   SDValue R = Op.getOperand(0);
15908   SDValue Amt = Op.getOperand(1);
15909
15910   // Optimize shl/srl/sra with constant shift amount.
15911   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15912     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15913       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15914
15915       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15916           (Subtarget->hasInt256() &&
15917            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15918           (Subtarget->hasAVX512() &&
15919            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15920         if (Op.getOpcode() == ISD::SHL)
15921           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15922                                             DAG);
15923         if (Op.getOpcode() == ISD::SRL)
15924           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15925                                             DAG);
15926         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15927           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15928                                             DAG);
15929       }
15930
15931       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
15932         unsigned NumElts = VT.getVectorNumElements();
15933         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
15934
15935         if (Op.getOpcode() == ISD::SHL) {
15936           // Make a large shift.
15937           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
15938                                                    R, ShiftAmt, DAG);
15939           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15940           // Zero out the rightmost bits.
15941           SmallVector<SDValue, 32> V(
15942               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
15943           return DAG.getNode(ISD::AND, dl, VT, SHL,
15944                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15945         }
15946         if (Op.getOpcode() == ISD::SRL) {
15947           // Make a large shift.
15948           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
15949                                                    R, ShiftAmt, DAG);
15950           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15951           // Zero out the leftmost bits.
15952           SmallVector<SDValue, 32> V(
15953               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
15954           return DAG.getNode(ISD::AND, dl, VT, SRL,
15955                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15956         }
15957         if (Op.getOpcode() == ISD::SRA) {
15958           if (ShiftAmt == 7) {
15959             // R s>> 7  ===  R s< 0
15960             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15961             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15962           }
15963
15964           // R s>> a === ((R u>> a) ^ m) - m
15965           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15966           SmallVector<SDValue, 32> V(NumElts,
15967                                      DAG.getConstant(128 >> ShiftAmt, MVT::i8));
15968           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15969           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15970           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15971           return Res;
15972         }
15973         llvm_unreachable("Unknown shift opcode.");
15974       }
15975     }
15976   }
15977
15978   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15979   if (!Subtarget->is64Bit() &&
15980       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15981       Amt.getOpcode() == ISD::BITCAST &&
15982       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15983     Amt = Amt.getOperand(0);
15984     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15985                      VT.getVectorNumElements();
15986     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15987     uint64_t ShiftAmt = 0;
15988     for (unsigned i = 0; i != Ratio; ++i) {
15989       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15990       if (!C)
15991         return SDValue();
15992       // 6 == Log2(64)
15993       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15994     }
15995     // Check remaining shift amounts.
15996     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15997       uint64_t ShAmt = 0;
15998       for (unsigned j = 0; j != Ratio; ++j) {
15999         ConstantSDNode *C =
16000           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16001         if (!C)
16002           return SDValue();
16003         // 6 == Log2(64)
16004         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16005       }
16006       if (ShAmt != ShiftAmt)
16007         return SDValue();
16008     }
16009     switch (Op.getOpcode()) {
16010     default:
16011       llvm_unreachable("Unknown shift opcode!");
16012     case ISD::SHL:
16013       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16014                                         DAG);
16015     case ISD::SRL:
16016       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16017                                         DAG);
16018     case ISD::SRA:
16019       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16020                                         DAG);
16021     }
16022   }
16023
16024   return SDValue();
16025 }
16026
16027 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16028                                         const X86Subtarget* Subtarget) {
16029   MVT VT = Op.getSimpleValueType();
16030   SDLoc dl(Op);
16031   SDValue R = Op.getOperand(0);
16032   SDValue Amt = Op.getOperand(1);
16033
16034   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16035       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16036       (Subtarget->hasInt256() &&
16037        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16038         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16039        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16040     SDValue BaseShAmt;
16041     EVT EltVT = VT.getVectorElementType();
16042
16043     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16044       // Check if this build_vector node is doing a splat.
16045       // If so, then set BaseShAmt equal to the splat value.
16046       BaseShAmt = BV->getSplatValue();
16047       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16048         BaseShAmt = SDValue();
16049     } else {
16050       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16051         Amt = Amt.getOperand(0);
16052
16053       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16054       if (SVN && SVN->isSplat()) {
16055         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16056         SDValue InVec = Amt.getOperand(0);
16057         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16058           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16059                  "Unexpected shuffle index found!");
16060           BaseShAmt = InVec.getOperand(SplatIdx);
16061         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16062            if (ConstantSDNode *C =
16063                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16064              if (C->getZExtValue() == SplatIdx)
16065                BaseShAmt = InVec.getOperand(1);
16066            }
16067         }
16068
16069         if (!BaseShAmt)
16070           // Avoid introducing an extract element from a shuffle.
16071           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16072                                     DAG.getIntPtrConstant(SplatIdx));
16073       }
16074     }
16075
16076     if (BaseShAmt.getNode()) {
16077       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16078       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16079         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16080       else if (EltVT.bitsLT(MVT::i32))
16081         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16082
16083       switch (Op.getOpcode()) {
16084       default:
16085         llvm_unreachable("Unknown shift opcode!");
16086       case ISD::SHL:
16087         switch (VT.SimpleTy) {
16088         default: return SDValue();
16089         case MVT::v2i64:
16090         case MVT::v4i32:
16091         case MVT::v8i16:
16092         case MVT::v4i64:
16093         case MVT::v8i32:
16094         case MVT::v16i16:
16095         case MVT::v16i32:
16096         case MVT::v8i64:
16097           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16098         }
16099       case ISD::SRA:
16100         switch (VT.SimpleTy) {
16101         default: return SDValue();
16102         case MVT::v4i32:
16103         case MVT::v8i16:
16104         case MVT::v8i32:
16105         case MVT::v16i16:
16106         case MVT::v16i32:
16107         case MVT::v8i64:
16108           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16109         }
16110       case ISD::SRL:
16111         switch (VT.SimpleTy) {
16112         default: return SDValue();
16113         case MVT::v2i64:
16114         case MVT::v4i32:
16115         case MVT::v8i16:
16116         case MVT::v4i64:
16117         case MVT::v8i32:
16118         case MVT::v16i16:
16119         case MVT::v16i32:
16120         case MVT::v8i64:
16121           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16122         }
16123       }
16124     }
16125   }
16126
16127   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16128   if (!Subtarget->is64Bit() &&
16129       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16130       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16131       Amt.getOpcode() == ISD::BITCAST &&
16132       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16133     Amt = Amt.getOperand(0);
16134     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16135                      VT.getVectorNumElements();
16136     std::vector<SDValue> Vals(Ratio);
16137     for (unsigned i = 0; i != Ratio; ++i)
16138       Vals[i] = Amt.getOperand(i);
16139     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16140       for (unsigned j = 0; j != Ratio; ++j)
16141         if (Vals[j] != Amt.getOperand(i + j))
16142           return SDValue();
16143     }
16144     switch (Op.getOpcode()) {
16145     default:
16146       llvm_unreachable("Unknown shift opcode!");
16147     case ISD::SHL:
16148       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16149     case ISD::SRL:
16150       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16151     case ISD::SRA:
16152       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16153     }
16154   }
16155
16156   return SDValue();
16157 }
16158
16159 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16160                           SelectionDAG &DAG) {
16161   MVT VT = Op.getSimpleValueType();
16162   SDLoc dl(Op);
16163   SDValue R = Op.getOperand(0);
16164   SDValue Amt = Op.getOperand(1);
16165
16166   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16167   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16168
16169   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16170     return V;
16171
16172   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16173       return V;
16174
16175   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16176     return Op;
16177
16178   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16179   if (Subtarget->hasInt256()) {
16180     if (Op.getOpcode() == ISD::SRL &&
16181         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16182          VT == MVT::v4i64 || VT == MVT::v8i32))
16183       return Op;
16184     if (Op.getOpcode() == ISD::SHL &&
16185         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16186          VT == MVT::v4i64 || VT == MVT::v8i32))
16187       return Op;
16188     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16189       return Op;
16190   }
16191
16192   // If possible, lower this packed shift into a vector multiply instead of
16193   // expanding it into a sequence of scalar shifts.
16194   // Do this only if the vector shift count is a constant build_vector.
16195   if (Op.getOpcode() == ISD::SHL &&
16196       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16197        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16198       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16199     SmallVector<SDValue, 8> Elts;
16200     EVT SVT = VT.getScalarType();
16201     unsigned SVTBits = SVT.getSizeInBits();
16202     const APInt &One = APInt(SVTBits, 1);
16203     unsigned NumElems = VT.getVectorNumElements();
16204
16205     for (unsigned i=0; i !=NumElems; ++i) {
16206       SDValue Op = Amt->getOperand(i);
16207       if (Op->getOpcode() == ISD::UNDEF) {
16208         Elts.push_back(Op);
16209         continue;
16210       }
16211
16212       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16213       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16214       uint64_t ShAmt = C.getZExtValue();
16215       if (ShAmt >= SVTBits) {
16216         Elts.push_back(DAG.getUNDEF(SVT));
16217         continue;
16218       }
16219       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16220     }
16221     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16222     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16223   }
16224
16225   // Lower SHL with variable shift amount.
16226   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16227     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16228
16229     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16230     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16231     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16232     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16233   }
16234
16235   // If possible, lower this shift as a sequence of two shifts by
16236   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16237   // Example:
16238   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16239   //
16240   // Could be rewritten as:
16241   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16242   //
16243   // The advantage is that the two shifts from the example would be
16244   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16245   // the vector shift into four scalar shifts plus four pairs of vector
16246   // insert/extract.
16247   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16248       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16249     unsigned TargetOpcode = X86ISD::MOVSS;
16250     bool CanBeSimplified;
16251     // The splat value for the first packed shift (the 'X' from the example).
16252     SDValue Amt1 = Amt->getOperand(0);
16253     // The splat value for the second packed shift (the 'Y' from the example).
16254     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16255                                         Amt->getOperand(2);
16256
16257     // See if it is possible to replace this node with a sequence of
16258     // two shifts followed by a MOVSS/MOVSD
16259     if (VT == MVT::v4i32) {
16260       // Check if it is legal to use a MOVSS.
16261       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16262                         Amt2 == Amt->getOperand(3);
16263       if (!CanBeSimplified) {
16264         // Otherwise, check if we can still simplify this node using a MOVSD.
16265         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16266                           Amt->getOperand(2) == Amt->getOperand(3);
16267         TargetOpcode = X86ISD::MOVSD;
16268         Amt2 = Amt->getOperand(2);
16269       }
16270     } else {
16271       // Do similar checks for the case where the machine value type
16272       // is MVT::v8i16.
16273       CanBeSimplified = Amt1 == Amt->getOperand(1);
16274       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16275         CanBeSimplified = Amt2 == Amt->getOperand(i);
16276
16277       if (!CanBeSimplified) {
16278         TargetOpcode = X86ISD::MOVSD;
16279         CanBeSimplified = true;
16280         Amt2 = Amt->getOperand(4);
16281         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16282           CanBeSimplified = Amt1 == Amt->getOperand(i);
16283         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16284           CanBeSimplified = Amt2 == Amt->getOperand(j);
16285       }
16286     }
16287
16288     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16289         isa<ConstantSDNode>(Amt2)) {
16290       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16291       EVT CastVT = MVT::v4i32;
16292       SDValue Splat1 =
16293         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16294       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16295       SDValue Splat2 =
16296         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16297       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16298       if (TargetOpcode == X86ISD::MOVSD)
16299         CastVT = MVT::v2i64;
16300       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16301       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16302       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16303                                             BitCast1, DAG);
16304       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16305     }
16306   }
16307
16308   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16309     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16310
16311     // a = a << 5;
16312     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16313     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16314
16315     // Turn 'a' into a mask suitable for VSELECT
16316     SDValue VSelM = DAG.getConstant(0x80, VT);
16317     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16318     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16319
16320     SDValue CM1 = DAG.getConstant(0x0f, VT);
16321     SDValue CM2 = DAG.getConstant(0x3f, VT);
16322
16323     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16324     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16325     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16326     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16327     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16328
16329     // a += a
16330     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16331     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16332     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16333
16334     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16335     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16336     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16337     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16338     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16339
16340     // a += a
16341     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16342     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16343     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16344
16345     // return VSELECT(r, r+r, a);
16346     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16347                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16348     return R;
16349   }
16350
16351   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16352   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16353   // solution better.
16354   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16355     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16356     unsigned ExtOpc =
16357         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16358     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16359     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16360     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16361                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16362   }
16363
16364   // Decompose 256-bit shifts into smaller 128-bit shifts.
16365   if (VT.is256BitVector()) {
16366     unsigned NumElems = VT.getVectorNumElements();
16367     MVT EltVT = VT.getVectorElementType();
16368     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16369
16370     // Extract the two vectors
16371     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16372     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16373
16374     // Recreate the shift amount vectors
16375     SDValue Amt1, Amt2;
16376     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16377       // Constant shift amount
16378       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16379       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16380       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16381
16382       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16383       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16384     } else {
16385       // Variable shift amount
16386       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16387       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16388     }
16389
16390     // Issue new vector shifts for the smaller types
16391     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16392     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16393
16394     // Concatenate the result back
16395     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16396   }
16397
16398   return SDValue();
16399 }
16400
16401 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16402   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16403   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16404   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16405   // has only one use.
16406   SDNode *N = Op.getNode();
16407   SDValue LHS = N->getOperand(0);
16408   SDValue RHS = N->getOperand(1);
16409   unsigned BaseOp = 0;
16410   unsigned Cond = 0;
16411   SDLoc DL(Op);
16412   switch (Op.getOpcode()) {
16413   default: llvm_unreachable("Unknown ovf instruction!");
16414   case ISD::SADDO:
16415     // A subtract of one will be selected as a INC. Note that INC doesn't
16416     // set CF, so we can't do this for UADDO.
16417     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16418       if (C->isOne()) {
16419         BaseOp = X86ISD::INC;
16420         Cond = X86::COND_O;
16421         break;
16422       }
16423     BaseOp = X86ISD::ADD;
16424     Cond = X86::COND_O;
16425     break;
16426   case ISD::UADDO:
16427     BaseOp = X86ISD::ADD;
16428     Cond = X86::COND_B;
16429     break;
16430   case ISD::SSUBO:
16431     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16432     // set CF, so we can't do this for USUBO.
16433     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16434       if (C->isOne()) {
16435         BaseOp = X86ISD::DEC;
16436         Cond = X86::COND_O;
16437         break;
16438       }
16439     BaseOp = X86ISD::SUB;
16440     Cond = X86::COND_O;
16441     break;
16442   case ISD::USUBO:
16443     BaseOp = X86ISD::SUB;
16444     Cond = X86::COND_B;
16445     break;
16446   case ISD::SMULO:
16447     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16448     Cond = X86::COND_O;
16449     break;
16450   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16451     if (N->getValueType(0) == MVT::i8) {
16452       BaseOp = X86ISD::UMUL8;
16453       Cond = X86::COND_O;
16454       break;
16455     }
16456     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16457                                  MVT::i32);
16458     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16459
16460     SDValue SetCC =
16461       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16462                   DAG.getConstant(X86::COND_O, MVT::i32),
16463                   SDValue(Sum.getNode(), 2));
16464
16465     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16466   }
16467   }
16468
16469   // Also sets EFLAGS.
16470   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16471   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16472
16473   SDValue SetCC =
16474     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16475                 DAG.getConstant(Cond, MVT::i32),
16476                 SDValue(Sum.getNode(), 1));
16477
16478   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16479 }
16480
16481 /// Returns true if the operand type is exactly twice the native width, and
16482 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16483 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16484 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16485 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16486   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16487
16488   if (OpWidth == 64)
16489     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16490   else if (OpWidth == 128)
16491     return Subtarget->hasCmpxchg16b();
16492   else
16493     return false;
16494 }
16495
16496 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16497   return needsCmpXchgNb(SI->getValueOperand()->getType());
16498 }
16499
16500 // Note: this turns large loads into lock cmpxchg8b/16b.
16501 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16502 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16503   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16504   return needsCmpXchgNb(PTy->getElementType());
16505 }
16506
16507 TargetLoweringBase::AtomicRMWExpansionKind
16508 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16509   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16510   const Type *MemType = AI->getType();
16511
16512   // If the operand is too big, we must see if cmpxchg8/16b is available
16513   // and default to library calls otherwise.
16514   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16515     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16516                                    : AtomicRMWExpansionKind::None;
16517   }
16518
16519   AtomicRMWInst::BinOp Op = AI->getOperation();
16520   switch (Op) {
16521   default:
16522     llvm_unreachable("Unknown atomic operation");
16523   case AtomicRMWInst::Xchg:
16524   case AtomicRMWInst::Add:
16525   case AtomicRMWInst::Sub:
16526     // It's better to use xadd, xsub or xchg for these in all cases.
16527     return AtomicRMWExpansionKind::None;
16528   case AtomicRMWInst::Or:
16529   case AtomicRMWInst::And:
16530   case AtomicRMWInst::Xor:
16531     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16532     // prefix to a normal instruction for these operations.
16533     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16534                             : AtomicRMWExpansionKind::None;
16535   case AtomicRMWInst::Nand:
16536   case AtomicRMWInst::Max:
16537   case AtomicRMWInst::Min:
16538   case AtomicRMWInst::UMax:
16539   case AtomicRMWInst::UMin:
16540     // These always require a non-trivial set of data operations on x86. We must
16541     // use a cmpxchg loop.
16542     return AtomicRMWExpansionKind::CmpXChg;
16543   }
16544 }
16545
16546 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16547   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16548   // no-sse2). There isn't any reason to disable it if the target processor
16549   // supports it.
16550   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16551 }
16552
16553 LoadInst *
16554 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16555   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16556   const Type *MemType = AI->getType();
16557   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16558   // there is no benefit in turning such RMWs into loads, and it is actually
16559   // harmful as it introduces a mfence.
16560   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16561     return nullptr;
16562
16563   auto Builder = IRBuilder<>(AI);
16564   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16565   auto SynchScope = AI->getSynchScope();
16566   // We must restrict the ordering to avoid generating loads with Release or
16567   // ReleaseAcquire orderings.
16568   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16569   auto Ptr = AI->getPointerOperand();
16570
16571   // Before the load we need a fence. Here is an example lifted from
16572   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16573   // is required:
16574   // Thread 0:
16575   //   x.store(1, relaxed);
16576   //   r1 = y.fetch_add(0, release);
16577   // Thread 1:
16578   //   y.fetch_add(42, acquire);
16579   //   r2 = x.load(relaxed);
16580   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16581   // lowered to just a load without a fence. A mfence flushes the store buffer,
16582   // making the optimization clearly correct.
16583   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16584   // otherwise, we might be able to be more agressive on relaxed idempotent
16585   // rmw. In practice, they do not look useful, so we don't try to be
16586   // especially clever.
16587   if (SynchScope == SingleThread) {
16588     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16589     // the IR level, so we must wrap it in an intrinsic.
16590     return nullptr;
16591   } else if (hasMFENCE(*Subtarget)) {
16592     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16593             Intrinsic::x86_sse2_mfence);
16594     Builder.CreateCall(MFence);
16595   } else {
16596     // FIXME: it might make sense to use a locked operation here but on a
16597     // different cache-line to prevent cache-line bouncing. In practice it
16598     // is probably a small win, and x86 processors without mfence are rare
16599     // enough that we do not bother.
16600     return nullptr;
16601   }
16602
16603   // Finally we can emit the atomic load.
16604   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16605           AI->getType()->getPrimitiveSizeInBits());
16606   Loaded->setAtomic(Order, SynchScope);
16607   AI->replaceAllUsesWith(Loaded);
16608   AI->eraseFromParent();
16609   return Loaded;
16610 }
16611
16612 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16613                                  SelectionDAG &DAG) {
16614   SDLoc dl(Op);
16615   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16616     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16617   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16618     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16619
16620   // The only fence that needs an instruction is a sequentially-consistent
16621   // cross-thread fence.
16622   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16623     if (hasMFENCE(*Subtarget))
16624       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16625
16626     SDValue Chain = Op.getOperand(0);
16627     SDValue Zero = DAG.getConstant(0, MVT::i32);
16628     SDValue Ops[] = {
16629       DAG.getRegister(X86::ESP, MVT::i32), // Base
16630       DAG.getTargetConstant(1, MVT::i8),   // Scale
16631       DAG.getRegister(0, MVT::i32),        // Index
16632       DAG.getTargetConstant(0, MVT::i32),  // Disp
16633       DAG.getRegister(0, MVT::i32),        // Segment.
16634       Zero,
16635       Chain
16636     };
16637     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16638     return SDValue(Res, 0);
16639   }
16640
16641   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16642   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16643 }
16644
16645 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16646                              SelectionDAG &DAG) {
16647   MVT T = Op.getSimpleValueType();
16648   SDLoc DL(Op);
16649   unsigned Reg = 0;
16650   unsigned size = 0;
16651   switch(T.SimpleTy) {
16652   default: llvm_unreachable("Invalid value type!");
16653   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16654   case MVT::i16: Reg = X86::AX;  size = 2; break;
16655   case MVT::i32: Reg = X86::EAX; size = 4; break;
16656   case MVT::i64:
16657     assert(Subtarget->is64Bit() && "Node not type legal!");
16658     Reg = X86::RAX; size = 8;
16659     break;
16660   }
16661   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16662                                   Op.getOperand(2), SDValue());
16663   SDValue Ops[] = { cpIn.getValue(0),
16664                     Op.getOperand(1),
16665                     Op.getOperand(3),
16666                     DAG.getTargetConstant(size, MVT::i8),
16667                     cpIn.getValue(1) };
16668   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16669   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16670   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16671                                            Ops, T, MMO);
16672
16673   SDValue cpOut =
16674     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16675   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16676                                       MVT::i32, cpOut.getValue(2));
16677   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16678                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16679
16680   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16681   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16682   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16683   return SDValue();
16684 }
16685
16686 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16687                             SelectionDAG &DAG) {
16688   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16689   MVT DstVT = Op.getSimpleValueType();
16690
16691   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16692     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16693     if (DstVT != MVT::f64)
16694       // This conversion needs to be expanded.
16695       return SDValue();
16696
16697     SDValue InVec = Op->getOperand(0);
16698     SDLoc dl(Op);
16699     unsigned NumElts = SrcVT.getVectorNumElements();
16700     EVT SVT = SrcVT.getVectorElementType();
16701
16702     // Widen the vector in input in the case of MVT::v2i32.
16703     // Example: from MVT::v2i32 to MVT::v4i32.
16704     SmallVector<SDValue, 16> Elts;
16705     for (unsigned i = 0, e = NumElts; i != e; ++i)
16706       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16707                                  DAG.getIntPtrConstant(i)));
16708
16709     // Explicitly mark the extra elements as Undef.
16710     Elts.append(NumElts, DAG.getUNDEF(SVT));
16711
16712     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16713     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16714     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16715     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16716                        DAG.getIntPtrConstant(0));
16717   }
16718
16719   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16720          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16721   assert((DstVT == MVT::i64 ||
16722           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16723          "Unexpected custom BITCAST");
16724   // i64 <=> MMX conversions are Legal.
16725   if (SrcVT==MVT::i64 && DstVT.isVector())
16726     return Op;
16727   if (DstVT==MVT::i64 && SrcVT.isVector())
16728     return Op;
16729   // MMX <=> MMX conversions are Legal.
16730   if (SrcVT.isVector() && DstVT.isVector())
16731     return Op;
16732   // All other conversions need to be expanded.
16733   return SDValue();
16734 }
16735
16736 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16737                           SelectionDAG &DAG) {
16738   SDNode *Node = Op.getNode();
16739   SDLoc dl(Node);
16740
16741   Op = Op.getOperand(0);
16742   EVT VT = Op.getValueType();
16743   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16744          "CTPOP lowering only implemented for 128/256-bit wide vector types");
16745
16746   unsigned NumElts = VT.getVectorNumElements();
16747   EVT EltVT = VT.getVectorElementType();
16748   unsigned Len = EltVT.getSizeInBits();
16749
16750   // This is the vectorized version of the "best" algorithm from
16751   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16752   // with a minor tweak to use a series of adds + shifts instead of vector
16753   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16754   //
16755   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16756   //  v8i32 => Always profitable
16757   //
16758   // FIXME: There a couple of possible improvements:
16759   //
16760   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16761   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16762   //
16763   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16764          "CTPOP not implemented for this vector element type.");
16765
16766   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16767   // extra legalization.
16768   bool NeedsBitcast = EltVT == MVT::i32;
16769   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16770
16771   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16772   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16773   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16774
16775   // v = v - ((v >> 1) & 0x55555555...)
16776   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16777   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16778   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16779   if (NeedsBitcast)
16780     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16781
16782   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16783   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16784   if (NeedsBitcast)
16785     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16786
16787   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16788   if (VT != And.getValueType())
16789     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16790   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16791
16792   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16793   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16794   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16795   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16796   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16797
16798   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16799   if (NeedsBitcast) {
16800     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16801     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16802     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16803   }
16804
16805   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16806   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16807   if (VT != AndRHS.getValueType()) {
16808     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16809     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16810   }
16811   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16812
16813   // v = (v + (v >> 4)) & 0x0F0F0F0F...
16814   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16815   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16816   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16817   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16818
16819   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16820   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16821   if (NeedsBitcast) {
16822     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16823     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16824   }
16825   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16826   if (VT != And.getValueType())
16827     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16828
16829   // The algorithm mentioned above uses:
16830   //    v = (v * 0x01010101...) >> (Len - 8)
16831   //
16832   // Change it to use vector adds + vector shifts which yield faster results on
16833   // Haswell than using vector integer multiplication.
16834   //
16835   // For i32 elements:
16836   //    v = v + (v >> 8)
16837   //    v = v + (v >> 16)
16838   //
16839   // For i64 elements:
16840   //    v = v + (v >> 8)
16841   //    v = v + (v >> 16)
16842   //    v = v + (v >> 32)
16843   //
16844   Add = And;
16845   SmallVector<SDValue, 8> Csts;
16846   for (unsigned i = 8; i <= Len/2; i *= 2) {
16847     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16848     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16849     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16850     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16851     Csts.clear();
16852   }
16853
16854   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16855   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16856   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16857   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16858   if (NeedsBitcast) {
16859     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16860     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16861   }
16862   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16863   if (VT != And.getValueType())
16864     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16865
16866   return And;
16867 }
16868
16869 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16870   SDNode *Node = Op.getNode();
16871   SDLoc dl(Node);
16872   EVT T = Node->getValueType(0);
16873   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16874                               DAG.getConstant(0, T), Node->getOperand(2));
16875   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16876                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16877                        Node->getOperand(0),
16878                        Node->getOperand(1), negOp,
16879                        cast<AtomicSDNode>(Node)->getMemOperand(),
16880                        cast<AtomicSDNode>(Node)->getOrdering(),
16881                        cast<AtomicSDNode>(Node)->getSynchScope());
16882 }
16883
16884 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16885   SDNode *Node = Op.getNode();
16886   SDLoc dl(Node);
16887   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16888
16889   // Convert seq_cst store -> xchg
16890   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16891   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16892   //        (The only way to get a 16-byte store is cmpxchg16b)
16893   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16894   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16895       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16896     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16897                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16898                                  Node->getOperand(0),
16899                                  Node->getOperand(1), Node->getOperand(2),
16900                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16901                                  cast<AtomicSDNode>(Node)->getOrdering(),
16902                                  cast<AtomicSDNode>(Node)->getSynchScope());
16903     return Swap.getValue(1);
16904   }
16905   // Other atomic stores have a simple pattern.
16906   return Op;
16907 }
16908
16909 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16910   EVT VT = Op.getNode()->getSimpleValueType(0);
16911
16912   // Let legalize expand this if it isn't a legal type yet.
16913   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16914     return SDValue();
16915
16916   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16917
16918   unsigned Opc;
16919   bool ExtraOp = false;
16920   switch (Op.getOpcode()) {
16921   default: llvm_unreachable("Invalid code");
16922   case ISD::ADDC: Opc = X86ISD::ADD; break;
16923   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16924   case ISD::SUBC: Opc = X86ISD::SUB; break;
16925   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16926   }
16927
16928   if (!ExtraOp)
16929     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16930                        Op.getOperand(1));
16931   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16932                      Op.getOperand(1), Op.getOperand(2));
16933 }
16934
16935 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16936                             SelectionDAG &DAG) {
16937   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16938
16939   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16940   // which returns the values as { float, float } (in XMM0) or
16941   // { double, double } (which is returned in XMM0, XMM1).
16942   SDLoc dl(Op);
16943   SDValue Arg = Op.getOperand(0);
16944   EVT ArgVT = Arg.getValueType();
16945   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16946
16947   TargetLowering::ArgListTy Args;
16948   TargetLowering::ArgListEntry Entry;
16949
16950   Entry.Node = Arg;
16951   Entry.Ty = ArgTy;
16952   Entry.isSExt = false;
16953   Entry.isZExt = false;
16954   Args.push_back(Entry);
16955
16956   bool isF64 = ArgVT == MVT::f64;
16957   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16958   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16959   // the results are returned via SRet in memory.
16960   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16962   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16963
16964   Type *RetTy = isF64
16965     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
16966     : (Type*)VectorType::get(ArgTy, 4);
16967
16968   TargetLowering::CallLoweringInfo CLI(DAG);
16969   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16970     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16971
16972   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16973
16974   if (isF64)
16975     // Returned in xmm0 and xmm1.
16976     return CallResult.first;
16977
16978   // Returned in bits 0:31 and 32:64 xmm0.
16979   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16980                                CallResult.first, DAG.getIntPtrConstant(0));
16981   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16982                                CallResult.first, DAG.getIntPtrConstant(1));
16983   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16984   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16985 }
16986
16987 /// LowerOperation - Provide custom lowering hooks for some operations.
16988 ///
16989 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16990   switch (Op.getOpcode()) {
16991   default: llvm_unreachable("Should not custom lower this!");
16992   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16993   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16994     return LowerCMP_SWAP(Op, Subtarget, DAG);
16995   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
16996   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16997   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16998   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16999   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17000   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17001   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17002   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17003   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17004   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17005   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17006   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17007   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17008   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17009   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17010   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17011   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17012   case ISD::SHL_PARTS:
17013   case ISD::SRA_PARTS:
17014   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17015   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17016   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17017   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17018   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17019   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17020   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17021   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17022   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17023   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17024   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17025   case ISD::FABS:
17026   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17027   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17028   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17029   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17030   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17031   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17032   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17033   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17034   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17035   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17036   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17037   case ISD::INTRINSIC_VOID:
17038   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17039   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17040   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17041   case ISD::FRAME_TO_ARGS_OFFSET:
17042                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17043   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17044   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17045   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17046   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17047   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17048   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17049   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17050   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17051   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17052   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17053   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17054   case ISD::UMUL_LOHI:
17055   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17056   case ISD::SRA:
17057   case ISD::SRL:
17058   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17059   case ISD::SADDO:
17060   case ISD::UADDO:
17061   case ISD::SSUBO:
17062   case ISD::USUBO:
17063   case ISD::SMULO:
17064   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17065   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17066   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17067   case ISD::ADDC:
17068   case ISD::ADDE:
17069   case ISD::SUBC:
17070   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17071   case ISD::ADD:                return LowerADD(Op, DAG);
17072   case ISD::SUB:                return LowerSUB(Op, DAG);
17073   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17074   }
17075 }
17076
17077 /// ReplaceNodeResults - Replace a node with an illegal result type
17078 /// with a new node built out of custom code.
17079 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17080                                            SmallVectorImpl<SDValue>&Results,
17081                                            SelectionDAG &DAG) const {
17082   SDLoc dl(N);
17083   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17084   switch (N->getOpcode()) {
17085   default:
17086     llvm_unreachable("Do not know how to custom type legalize this operation!");
17087   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17088   case X86ISD::FMINC:
17089   case X86ISD::FMIN:
17090   case X86ISD::FMAXC:
17091   case X86ISD::FMAX: {
17092     EVT VT = N->getValueType(0);
17093     if (VT != MVT::v2f32)
17094       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17095     SDValue UNDEF = DAG.getUNDEF(VT);
17096     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17097                               N->getOperand(0), UNDEF);
17098     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17099                               N->getOperand(1), UNDEF);
17100     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17101     return;
17102   }
17103   case ISD::SIGN_EXTEND_INREG:
17104   case ISD::ADDC:
17105   case ISD::ADDE:
17106   case ISD::SUBC:
17107   case ISD::SUBE:
17108     // We don't want to expand or promote these.
17109     return;
17110   case ISD::SDIV:
17111   case ISD::UDIV:
17112   case ISD::SREM:
17113   case ISD::UREM:
17114   case ISD::SDIVREM:
17115   case ISD::UDIVREM: {
17116     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17117     Results.push_back(V);
17118     return;
17119   }
17120   case ISD::FP_TO_SINT:
17121   case ISD::FP_TO_UINT: {
17122     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17123
17124     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17125       return;
17126
17127     std::pair<SDValue,SDValue> Vals =
17128         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17129     SDValue FIST = Vals.first, StackSlot = Vals.second;
17130     if (FIST.getNode()) {
17131       EVT VT = N->getValueType(0);
17132       // Return a load from the stack slot.
17133       if (StackSlot.getNode())
17134         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17135                                       MachinePointerInfo(),
17136                                       false, false, false, 0));
17137       else
17138         Results.push_back(FIST);
17139     }
17140     return;
17141   }
17142   case ISD::UINT_TO_FP: {
17143     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17144     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17145         N->getValueType(0) != MVT::v2f32)
17146       return;
17147     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17148                                  N->getOperand(0));
17149     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17150                                      MVT::f64);
17151     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17152     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17153                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17154     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17155     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17156     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17157     return;
17158   }
17159   case ISD::FP_ROUND: {
17160     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17161         return;
17162     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17163     Results.push_back(V);
17164     return;
17165   }
17166   case ISD::INTRINSIC_W_CHAIN: {
17167     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17168     switch (IntNo) {
17169     default : llvm_unreachable("Do not know how to custom type "
17170                                "legalize this intrinsic operation!");
17171     case Intrinsic::x86_rdtsc:
17172       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17173                                      Results);
17174     case Intrinsic::x86_rdtscp:
17175       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17176                                      Results);
17177     case Intrinsic::x86_rdpmc:
17178       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17179     }
17180   }
17181   case ISD::READCYCLECOUNTER: {
17182     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17183                                    Results);
17184   }
17185   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17186     EVT T = N->getValueType(0);
17187     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17188     bool Regs64bit = T == MVT::i128;
17189     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17190     SDValue cpInL, cpInH;
17191     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17192                         DAG.getConstant(0, HalfT));
17193     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17194                         DAG.getConstant(1, HalfT));
17195     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17196                              Regs64bit ? X86::RAX : X86::EAX,
17197                              cpInL, SDValue());
17198     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17199                              Regs64bit ? X86::RDX : X86::EDX,
17200                              cpInH, cpInL.getValue(1));
17201     SDValue swapInL, swapInH;
17202     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17203                           DAG.getConstant(0, HalfT));
17204     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17205                           DAG.getConstant(1, HalfT));
17206     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17207                                Regs64bit ? X86::RBX : X86::EBX,
17208                                swapInL, cpInH.getValue(1));
17209     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17210                                Regs64bit ? X86::RCX : X86::ECX,
17211                                swapInH, swapInL.getValue(1));
17212     SDValue Ops[] = { swapInH.getValue(0),
17213                       N->getOperand(1),
17214                       swapInH.getValue(1) };
17215     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17216     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17217     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17218                                   X86ISD::LCMPXCHG8_DAG;
17219     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17220     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17221                                         Regs64bit ? X86::RAX : X86::EAX,
17222                                         HalfT, Result.getValue(1));
17223     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17224                                         Regs64bit ? X86::RDX : X86::EDX,
17225                                         HalfT, cpOutL.getValue(2));
17226     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17227
17228     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17229                                         MVT::i32, cpOutH.getValue(2));
17230     SDValue Success =
17231         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17232                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17233     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17234
17235     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17236     Results.push_back(Success);
17237     Results.push_back(EFLAGS.getValue(1));
17238     return;
17239   }
17240   case ISD::ATOMIC_SWAP:
17241   case ISD::ATOMIC_LOAD_ADD:
17242   case ISD::ATOMIC_LOAD_SUB:
17243   case ISD::ATOMIC_LOAD_AND:
17244   case ISD::ATOMIC_LOAD_OR:
17245   case ISD::ATOMIC_LOAD_XOR:
17246   case ISD::ATOMIC_LOAD_NAND:
17247   case ISD::ATOMIC_LOAD_MIN:
17248   case ISD::ATOMIC_LOAD_MAX:
17249   case ISD::ATOMIC_LOAD_UMIN:
17250   case ISD::ATOMIC_LOAD_UMAX:
17251   case ISD::ATOMIC_LOAD: {
17252     // Delegate to generic TypeLegalization. Situations we can really handle
17253     // should have already been dealt with by AtomicExpandPass.cpp.
17254     break;
17255   }
17256   case ISD::BITCAST: {
17257     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17258     EVT DstVT = N->getValueType(0);
17259     EVT SrcVT = N->getOperand(0)->getValueType(0);
17260
17261     if (SrcVT != MVT::f64 ||
17262         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17263       return;
17264
17265     unsigned NumElts = DstVT.getVectorNumElements();
17266     EVT SVT = DstVT.getVectorElementType();
17267     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17268     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17269                                    MVT::v2f64, N->getOperand(0));
17270     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17271
17272     if (ExperimentalVectorWideningLegalization) {
17273       // If we are legalizing vectors by widening, we already have the desired
17274       // legal vector type, just return it.
17275       Results.push_back(ToVecInt);
17276       return;
17277     }
17278
17279     SmallVector<SDValue, 8> Elts;
17280     for (unsigned i = 0, e = NumElts; i != e; ++i)
17281       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17282                                    ToVecInt, DAG.getIntPtrConstant(i)));
17283
17284     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17285   }
17286   }
17287 }
17288
17289 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17290   switch (Opcode) {
17291   default: return nullptr;
17292   case X86ISD::BSF:                return "X86ISD::BSF";
17293   case X86ISD::BSR:                return "X86ISD::BSR";
17294   case X86ISD::SHLD:               return "X86ISD::SHLD";
17295   case X86ISD::SHRD:               return "X86ISD::SHRD";
17296   case X86ISD::FAND:               return "X86ISD::FAND";
17297   case X86ISD::FANDN:              return "X86ISD::FANDN";
17298   case X86ISD::FOR:                return "X86ISD::FOR";
17299   case X86ISD::FXOR:               return "X86ISD::FXOR";
17300   case X86ISD::FSRL:               return "X86ISD::FSRL";
17301   case X86ISD::FILD:               return "X86ISD::FILD";
17302   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17303   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17304   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17305   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17306   case X86ISD::FLD:                return "X86ISD::FLD";
17307   case X86ISD::FST:                return "X86ISD::FST";
17308   case X86ISD::CALL:               return "X86ISD::CALL";
17309   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17310   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17311   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17312   case X86ISD::BT:                 return "X86ISD::BT";
17313   case X86ISD::CMP:                return "X86ISD::CMP";
17314   case X86ISD::COMI:               return "X86ISD::COMI";
17315   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17316   case X86ISD::CMPM:               return "X86ISD::CMPM";
17317   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17318   case X86ISD::SETCC:              return "X86ISD::SETCC";
17319   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17320   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17321   case X86ISD::CMOV:               return "X86ISD::CMOV";
17322   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17323   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17324   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17325   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17326   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17327   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17328   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17329   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17330   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17331   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17332   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17333   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17334   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17335   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17336   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17337   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17338   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17339   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17340   case X86ISD::HADD:               return "X86ISD::HADD";
17341   case X86ISD::HSUB:               return "X86ISD::HSUB";
17342   case X86ISD::FHADD:              return "X86ISD::FHADD";
17343   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17344   case X86ISD::UMAX:               return "X86ISD::UMAX";
17345   case X86ISD::UMIN:               return "X86ISD::UMIN";
17346   case X86ISD::SMAX:               return "X86ISD::SMAX";
17347   case X86ISD::SMIN:               return "X86ISD::SMIN";
17348   case X86ISD::FMAX:               return "X86ISD::FMAX";
17349   case X86ISD::FMIN:               return "X86ISD::FMIN";
17350   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17351   case X86ISD::FMINC:              return "X86ISD::FMINC";
17352   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17353   case X86ISD::FRCP:               return "X86ISD::FRCP";
17354   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17355   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17356   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17357   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17358   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17359   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17360   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17361   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17362   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17363   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17364   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17365   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17366   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17367   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17368   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17369   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17370   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17371   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17372   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17373   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17374   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17375   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17376   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17377   case X86ISD::VSHL:               return "X86ISD::VSHL";
17378   case X86ISD::VSRL:               return "X86ISD::VSRL";
17379   case X86ISD::VSRA:               return "X86ISD::VSRA";
17380   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17381   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17382   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17383   case X86ISD::CMPP:               return "X86ISD::CMPP";
17384   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17385   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17386   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17387   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17388   case X86ISD::ADD:                return "X86ISD::ADD";
17389   case X86ISD::SUB:                return "X86ISD::SUB";
17390   case X86ISD::ADC:                return "X86ISD::ADC";
17391   case X86ISD::SBB:                return "X86ISD::SBB";
17392   case X86ISD::SMUL:               return "X86ISD::SMUL";
17393   case X86ISD::UMUL:               return "X86ISD::UMUL";
17394   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17395   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17396   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17397   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17398   case X86ISD::INC:                return "X86ISD::INC";
17399   case X86ISD::DEC:                return "X86ISD::DEC";
17400   case X86ISD::OR:                 return "X86ISD::OR";
17401   case X86ISD::XOR:                return "X86ISD::XOR";
17402   case X86ISD::AND:                return "X86ISD::AND";
17403   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17404   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17405   case X86ISD::PTEST:              return "X86ISD::PTEST";
17406   case X86ISD::TESTP:              return "X86ISD::TESTP";
17407   case X86ISD::TESTM:              return "X86ISD::TESTM";
17408   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17409   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17410   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17411   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17412   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17413   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17414   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17415   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17416   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17417   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17418   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17419   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17420   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17421   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17422   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17423   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17424   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17425   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17426   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17427   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17428   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17429   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17430   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17431   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17432   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17433   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17434   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17435   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17436   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17437   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17438   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17439   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17440   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17441   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17442   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17443   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17444   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17445   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17446   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17447   case X86ISD::SAHF:               return "X86ISD::SAHF";
17448   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17449   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17450   case X86ISD::FMADD:              return "X86ISD::FMADD";
17451   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17452   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17453   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17454   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17455   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17456   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17457   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17458   case X86ISD::XTEST:              return "X86ISD::XTEST";
17459   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17460   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17461   case X86ISD::SELECT:             return "X86ISD::SELECT";
17462   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17463   case X86ISD::RCP28:              return "X86ISD::RCP28";
17464   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17465   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17466   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17467   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17468   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17469   }
17470 }
17471
17472 // isLegalAddressingMode - Return true if the addressing mode represented
17473 // by AM is legal for this target, for a load/store of the specified type.
17474 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17475                                               Type *Ty) const {
17476   // X86 supports extremely general addressing modes.
17477   CodeModel::Model M = getTargetMachine().getCodeModel();
17478   Reloc::Model R = getTargetMachine().getRelocationModel();
17479
17480   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17481   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17482     return false;
17483
17484   if (AM.BaseGV) {
17485     unsigned GVFlags =
17486       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17487
17488     // If a reference to this global requires an extra load, we can't fold it.
17489     if (isGlobalStubReference(GVFlags))
17490       return false;
17491
17492     // If BaseGV requires a register for the PIC base, we cannot also have a
17493     // BaseReg specified.
17494     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17495       return false;
17496
17497     // If lower 4G is not available, then we must use rip-relative addressing.
17498     if ((M != CodeModel::Small || R != Reloc::Static) &&
17499         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17500       return false;
17501   }
17502
17503   switch (AM.Scale) {
17504   case 0:
17505   case 1:
17506   case 2:
17507   case 4:
17508   case 8:
17509     // These scales always work.
17510     break;
17511   case 3:
17512   case 5:
17513   case 9:
17514     // These scales are formed with basereg+scalereg.  Only accept if there is
17515     // no basereg yet.
17516     if (AM.HasBaseReg)
17517       return false;
17518     break;
17519   default:  // Other stuff never works.
17520     return false;
17521   }
17522
17523   return true;
17524 }
17525
17526 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17527   unsigned Bits = Ty->getScalarSizeInBits();
17528
17529   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17530   // particularly cheaper than those without.
17531   if (Bits == 8)
17532     return false;
17533
17534   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17535   // variable shifts just as cheap as scalar ones.
17536   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17537     return false;
17538
17539   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17540   // fully general vector.
17541   return true;
17542 }
17543
17544 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17545   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17546     return false;
17547   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17548   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17549   return NumBits1 > NumBits2;
17550 }
17551
17552 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17553   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17554     return false;
17555
17556   if (!isTypeLegal(EVT::getEVT(Ty1)))
17557     return false;
17558
17559   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17560
17561   // Assuming the caller doesn't have a zeroext or signext return parameter,
17562   // truncation all the way down to i1 is valid.
17563   return true;
17564 }
17565
17566 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17567   return isInt<32>(Imm);
17568 }
17569
17570 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17571   // Can also use sub to handle negated immediates.
17572   return isInt<32>(Imm);
17573 }
17574
17575 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17576   if (!VT1.isInteger() || !VT2.isInteger())
17577     return false;
17578   unsigned NumBits1 = VT1.getSizeInBits();
17579   unsigned NumBits2 = VT2.getSizeInBits();
17580   return NumBits1 > NumBits2;
17581 }
17582
17583 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17584   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17585   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17586 }
17587
17588 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17589   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17590   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17591 }
17592
17593 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17594   EVT VT1 = Val.getValueType();
17595   if (isZExtFree(VT1, VT2))
17596     return true;
17597
17598   if (Val.getOpcode() != ISD::LOAD)
17599     return false;
17600
17601   if (!VT1.isSimple() || !VT1.isInteger() ||
17602       !VT2.isSimple() || !VT2.isInteger())
17603     return false;
17604
17605   switch (VT1.getSimpleVT().SimpleTy) {
17606   default: break;
17607   case MVT::i8:
17608   case MVT::i16:
17609   case MVT::i32:
17610     // X86 has 8, 16, and 32-bit zero-extending loads.
17611     return true;
17612   }
17613
17614   return false;
17615 }
17616
17617 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17618
17619 bool
17620 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17621   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17622     return false;
17623
17624   VT = VT.getScalarType();
17625
17626   if (!VT.isSimple())
17627     return false;
17628
17629   switch (VT.getSimpleVT().SimpleTy) {
17630   case MVT::f32:
17631   case MVT::f64:
17632     return true;
17633   default:
17634     break;
17635   }
17636
17637   return false;
17638 }
17639
17640 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17641   // i16 instructions are longer (0x66 prefix) and potentially slower.
17642   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17643 }
17644
17645 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17646 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17647 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17648 /// are assumed to be legal.
17649 bool
17650 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17651                                       EVT VT) const {
17652   if (!VT.isSimple())
17653     return false;
17654
17655   // Very little shuffling can be done for 64-bit vectors right now.
17656   if (VT.getSizeInBits() == 64)
17657     return false;
17658
17659   // We only care that the types being shuffled are legal. The lowering can
17660   // handle any possible shuffle mask that results.
17661   return isTypeLegal(VT.getSimpleVT());
17662 }
17663
17664 bool
17665 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17666                                           EVT VT) const {
17667   // Just delegate to the generic legality, clear masks aren't special.
17668   return isShuffleMaskLegal(Mask, VT);
17669 }
17670
17671 //===----------------------------------------------------------------------===//
17672 //                           X86 Scheduler Hooks
17673 //===----------------------------------------------------------------------===//
17674
17675 /// Utility function to emit xbegin specifying the start of an RTM region.
17676 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17677                                      const TargetInstrInfo *TII) {
17678   DebugLoc DL = MI->getDebugLoc();
17679
17680   const BasicBlock *BB = MBB->getBasicBlock();
17681   MachineFunction::iterator I = MBB;
17682   ++I;
17683
17684   // For the v = xbegin(), we generate
17685   //
17686   // thisMBB:
17687   //  xbegin sinkMBB
17688   //
17689   // mainMBB:
17690   //  eax = -1
17691   //
17692   // sinkMBB:
17693   //  v = eax
17694
17695   MachineBasicBlock *thisMBB = MBB;
17696   MachineFunction *MF = MBB->getParent();
17697   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17698   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17699   MF->insert(I, mainMBB);
17700   MF->insert(I, sinkMBB);
17701
17702   // Transfer the remainder of BB and its successor edges to sinkMBB.
17703   sinkMBB->splice(sinkMBB->begin(), MBB,
17704                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17705   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17706
17707   // thisMBB:
17708   //  xbegin sinkMBB
17709   //  # fallthrough to mainMBB
17710   //  # abortion to sinkMBB
17711   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17712   thisMBB->addSuccessor(mainMBB);
17713   thisMBB->addSuccessor(sinkMBB);
17714
17715   // mainMBB:
17716   //  EAX = -1
17717   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17718   mainMBB->addSuccessor(sinkMBB);
17719
17720   // sinkMBB:
17721   // EAX is live into the sinkMBB
17722   sinkMBB->addLiveIn(X86::EAX);
17723   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17724           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17725     .addReg(X86::EAX);
17726
17727   MI->eraseFromParent();
17728   return sinkMBB;
17729 }
17730
17731 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17732 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17733 // in the .td file.
17734 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17735                                        const TargetInstrInfo *TII) {
17736   unsigned Opc;
17737   switch (MI->getOpcode()) {
17738   default: llvm_unreachable("illegal opcode!");
17739   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17740   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17741   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17742   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17743   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17744   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17745   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17746   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17747   }
17748
17749   DebugLoc dl = MI->getDebugLoc();
17750   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17751
17752   unsigned NumArgs = MI->getNumOperands();
17753   for (unsigned i = 1; i < NumArgs; ++i) {
17754     MachineOperand &Op = MI->getOperand(i);
17755     if (!(Op.isReg() && Op.isImplicit()))
17756       MIB.addOperand(Op);
17757   }
17758   if (MI->hasOneMemOperand())
17759     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17760
17761   BuildMI(*BB, MI, dl,
17762     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17763     .addReg(X86::XMM0);
17764
17765   MI->eraseFromParent();
17766   return BB;
17767 }
17768
17769 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17770 // defs in an instruction pattern
17771 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17772                                        const TargetInstrInfo *TII) {
17773   unsigned Opc;
17774   switch (MI->getOpcode()) {
17775   default: llvm_unreachable("illegal opcode!");
17776   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17777   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17778   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17779   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17780   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17781   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17782   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17783   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17784   }
17785
17786   DebugLoc dl = MI->getDebugLoc();
17787   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17788
17789   unsigned NumArgs = MI->getNumOperands(); // remove the results
17790   for (unsigned i = 1; i < NumArgs; ++i) {
17791     MachineOperand &Op = MI->getOperand(i);
17792     if (!(Op.isReg() && Op.isImplicit()))
17793       MIB.addOperand(Op);
17794   }
17795   if (MI->hasOneMemOperand())
17796     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17797
17798   BuildMI(*BB, MI, dl,
17799     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17800     .addReg(X86::ECX);
17801
17802   MI->eraseFromParent();
17803   return BB;
17804 }
17805
17806 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17807                                       const X86Subtarget *Subtarget) {
17808   DebugLoc dl = MI->getDebugLoc();
17809   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17810   // Address into RAX/EAX, other two args into ECX, EDX.
17811   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17812   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17813   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17814   for (int i = 0; i < X86::AddrNumOperands; ++i)
17815     MIB.addOperand(MI->getOperand(i));
17816
17817   unsigned ValOps = X86::AddrNumOperands;
17818   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17819     .addReg(MI->getOperand(ValOps).getReg());
17820   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17821     .addReg(MI->getOperand(ValOps+1).getReg());
17822
17823   // The instruction doesn't actually take any operands though.
17824   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17825
17826   MI->eraseFromParent(); // The pseudo is gone now.
17827   return BB;
17828 }
17829
17830 MachineBasicBlock *
17831 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17832                                                  MachineBasicBlock *MBB) const {
17833   // Emit va_arg instruction on X86-64.
17834
17835   // Operands to this pseudo-instruction:
17836   // 0  ) Output        : destination address (reg)
17837   // 1-5) Input         : va_list address (addr, i64mem)
17838   // 6  ) ArgSize       : Size (in bytes) of vararg type
17839   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17840   // 8  ) Align         : Alignment of type
17841   // 9  ) EFLAGS (implicit-def)
17842
17843   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17844   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17845
17846   unsigned DestReg = MI->getOperand(0).getReg();
17847   MachineOperand &Base = MI->getOperand(1);
17848   MachineOperand &Scale = MI->getOperand(2);
17849   MachineOperand &Index = MI->getOperand(3);
17850   MachineOperand &Disp = MI->getOperand(4);
17851   MachineOperand &Segment = MI->getOperand(5);
17852   unsigned ArgSize = MI->getOperand(6).getImm();
17853   unsigned ArgMode = MI->getOperand(7).getImm();
17854   unsigned Align = MI->getOperand(8).getImm();
17855
17856   // Memory Reference
17857   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17858   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17859   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17860
17861   // Machine Information
17862   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17863   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17864   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17865   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17866   DebugLoc DL = MI->getDebugLoc();
17867
17868   // struct va_list {
17869   //   i32   gp_offset
17870   //   i32   fp_offset
17871   //   i64   overflow_area (address)
17872   //   i64   reg_save_area (address)
17873   // }
17874   // sizeof(va_list) = 24
17875   // alignment(va_list) = 8
17876
17877   unsigned TotalNumIntRegs = 6;
17878   unsigned TotalNumXMMRegs = 8;
17879   bool UseGPOffset = (ArgMode == 1);
17880   bool UseFPOffset = (ArgMode == 2);
17881   unsigned MaxOffset = TotalNumIntRegs * 8 +
17882                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17883
17884   /* Align ArgSize to a multiple of 8 */
17885   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17886   bool NeedsAlign = (Align > 8);
17887
17888   MachineBasicBlock *thisMBB = MBB;
17889   MachineBasicBlock *overflowMBB;
17890   MachineBasicBlock *offsetMBB;
17891   MachineBasicBlock *endMBB;
17892
17893   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17894   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17895   unsigned OffsetReg = 0;
17896
17897   if (!UseGPOffset && !UseFPOffset) {
17898     // If we only pull from the overflow region, we don't create a branch.
17899     // We don't need to alter control flow.
17900     OffsetDestReg = 0; // unused
17901     OverflowDestReg = DestReg;
17902
17903     offsetMBB = nullptr;
17904     overflowMBB = thisMBB;
17905     endMBB = thisMBB;
17906   } else {
17907     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17908     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17909     // If not, pull from overflow_area. (branch to overflowMBB)
17910     //
17911     //       thisMBB
17912     //         |     .
17913     //         |        .
17914     //     offsetMBB   overflowMBB
17915     //         |        .
17916     //         |     .
17917     //        endMBB
17918
17919     // Registers for the PHI in endMBB
17920     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17921     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17922
17923     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17924     MachineFunction *MF = MBB->getParent();
17925     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17926     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17927     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17928
17929     MachineFunction::iterator MBBIter = MBB;
17930     ++MBBIter;
17931
17932     // Insert the new basic blocks
17933     MF->insert(MBBIter, offsetMBB);
17934     MF->insert(MBBIter, overflowMBB);
17935     MF->insert(MBBIter, endMBB);
17936
17937     // Transfer the remainder of MBB and its successor edges to endMBB.
17938     endMBB->splice(endMBB->begin(), thisMBB,
17939                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17940     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17941
17942     // Make offsetMBB and overflowMBB successors of thisMBB
17943     thisMBB->addSuccessor(offsetMBB);
17944     thisMBB->addSuccessor(overflowMBB);
17945
17946     // endMBB is a successor of both offsetMBB and overflowMBB
17947     offsetMBB->addSuccessor(endMBB);
17948     overflowMBB->addSuccessor(endMBB);
17949
17950     // Load the offset value into a register
17951     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17952     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17953       .addOperand(Base)
17954       .addOperand(Scale)
17955       .addOperand(Index)
17956       .addDisp(Disp, UseFPOffset ? 4 : 0)
17957       .addOperand(Segment)
17958       .setMemRefs(MMOBegin, MMOEnd);
17959
17960     // Check if there is enough room left to pull this argument.
17961     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17962       .addReg(OffsetReg)
17963       .addImm(MaxOffset + 8 - ArgSizeA8);
17964
17965     // Branch to "overflowMBB" if offset >= max
17966     // Fall through to "offsetMBB" otherwise
17967     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17968       .addMBB(overflowMBB);
17969   }
17970
17971   // In offsetMBB, emit code to use the reg_save_area.
17972   if (offsetMBB) {
17973     assert(OffsetReg != 0);
17974
17975     // Read the reg_save_area address.
17976     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17977     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17978       .addOperand(Base)
17979       .addOperand(Scale)
17980       .addOperand(Index)
17981       .addDisp(Disp, 16)
17982       .addOperand(Segment)
17983       .setMemRefs(MMOBegin, MMOEnd);
17984
17985     // Zero-extend the offset
17986     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17987       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17988         .addImm(0)
17989         .addReg(OffsetReg)
17990         .addImm(X86::sub_32bit);
17991
17992     // Add the offset to the reg_save_area to get the final address.
17993     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17994       .addReg(OffsetReg64)
17995       .addReg(RegSaveReg);
17996
17997     // Compute the offset for the next argument
17998     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17999     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18000       .addReg(OffsetReg)
18001       .addImm(UseFPOffset ? 16 : 8);
18002
18003     // Store it back into the va_list.
18004     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18005       .addOperand(Base)
18006       .addOperand(Scale)
18007       .addOperand(Index)
18008       .addDisp(Disp, UseFPOffset ? 4 : 0)
18009       .addOperand(Segment)
18010       .addReg(NextOffsetReg)
18011       .setMemRefs(MMOBegin, MMOEnd);
18012
18013     // Jump to endMBB
18014     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18015       .addMBB(endMBB);
18016   }
18017
18018   //
18019   // Emit code to use overflow area
18020   //
18021
18022   // Load the overflow_area address into a register.
18023   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18024   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18025     .addOperand(Base)
18026     .addOperand(Scale)
18027     .addOperand(Index)
18028     .addDisp(Disp, 8)
18029     .addOperand(Segment)
18030     .setMemRefs(MMOBegin, MMOEnd);
18031
18032   // If we need to align it, do so. Otherwise, just copy the address
18033   // to OverflowDestReg.
18034   if (NeedsAlign) {
18035     // Align the overflow address
18036     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18037     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18038
18039     // aligned_addr = (addr + (align-1)) & ~(align-1)
18040     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18041       .addReg(OverflowAddrReg)
18042       .addImm(Align-1);
18043
18044     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18045       .addReg(TmpReg)
18046       .addImm(~(uint64_t)(Align-1));
18047   } else {
18048     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18049       .addReg(OverflowAddrReg);
18050   }
18051
18052   // Compute the next overflow address after this argument.
18053   // (the overflow address should be kept 8-byte aligned)
18054   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18055   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18056     .addReg(OverflowDestReg)
18057     .addImm(ArgSizeA8);
18058
18059   // Store the new overflow address.
18060   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18061     .addOperand(Base)
18062     .addOperand(Scale)
18063     .addOperand(Index)
18064     .addDisp(Disp, 8)
18065     .addOperand(Segment)
18066     .addReg(NextAddrReg)
18067     .setMemRefs(MMOBegin, MMOEnd);
18068
18069   // If we branched, emit the PHI to the front of endMBB.
18070   if (offsetMBB) {
18071     BuildMI(*endMBB, endMBB->begin(), DL,
18072             TII->get(X86::PHI), DestReg)
18073       .addReg(OffsetDestReg).addMBB(offsetMBB)
18074       .addReg(OverflowDestReg).addMBB(overflowMBB);
18075   }
18076
18077   // Erase the pseudo instruction
18078   MI->eraseFromParent();
18079
18080   return endMBB;
18081 }
18082
18083 MachineBasicBlock *
18084 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18085                                                  MachineInstr *MI,
18086                                                  MachineBasicBlock *MBB) const {
18087   // Emit code to save XMM registers to the stack. The ABI says that the
18088   // number of registers to save is given in %al, so it's theoretically
18089   // possible to do an indirect jump trick to avoid saving all of them,
18090   // however this code takes a simpler approach and just executes all
18091   // of the stores if %al is non-zero. It's less code, and it's probably
18092   // easier on the hardware branch predictor, and stores aren't all that
18093   // expensive anyway.
18094
18095   // Create the new basic blocks. One block contains all the XMM stores,
18096   // and one block is the final destination regardless of whether any
18097   // stores were performed.
18098   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18099   MachineFunction *F = MBB->getParent();
18100   MachineFunction::iterator MBBIter = MBB;
18101   ++MBBIter;
18102   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18103   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18104   F->insert(MBBIter, XMMSaveMBB);
18105   F->insert(MBBIter, EndMBB);
18106
18107   // Transfer the remainder of MBB and its successor edges to EndMBB.
18108   EndMBB->splice(EndMBB->begin(), MBB,
18109                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18110   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18111
18112   // The original block will now fall through to the XMM save block.
18113   MBB->addSuccessor(XMMSaveMBB);
18114   // The XMMSaveMBB will fall through to the end block.
18115   XMMSaveMBB->addSuccessor(EndMBB);
18116
18117   // Now add the instructions.
18118   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18119   DebugLoc DL = MI->getDebugLoc();
18120
18121   unsigned CountReg = MI->getOperand(0).getReg();
18122   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18123   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18124
18125   if (!Subtarget->isTargetWin64()) {
18126     // If %al is 0, branch around the XMM save block.
18127     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18128     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18129     MBB->addSuccessor(EndMBB);
18130   }
18131
18132   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18133   // that was just emitted, but clearly shouldn't be "saved".
18134   assert((MI->getNumOperands() <= 3 ||
18135           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18136           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18137          && "Expected last argument to be EFLAGS");
18138   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18139   // In the XMM save block, save all the XMM argument registers.
18140   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18141     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18142     MachineMemOperand *MMO =
18143       F->getMachineMemOperand(
18144           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18145         MachineMemOperand::MOStore,
18146         /*Size=*/16, /*Align=*/16);
18147     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18148       .addFrameIndex(RegSaveFrameIndex)
18149       .addImm(/*Scale=*/1)
18150       .addReg(/*IndexReg=*/0)
18151       .addImm(/*Disp=*/Offset)
18152       .addReg(/*Segment=*/0)
18153       .addReg(MI->getOperand(i).getReg())
18154       .addMemOperand(MMO);
18155   }
18156
18157   MI->eraseFromParent();   // The pseudo instruction is gone now.
18158
18159   return EndMBB;
18160 }
18161
18162 // The EFLAGS operand of SelectItr might be missing a kill marker
18163 // because there were multiple uses of EFLAGS, and ISel didn't know
18164 // which to mark. Figure out whether SelectItr should have had a
18165 // kill marker, and set it if it should. Returns the correct kill
18166 // marker value.
18167 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18168                                      MachineBasicBlock* BB,
18169                                      const TargetRegisterInfo* TRI) {
18170   // Scan forward through BB for a use/def of EFLAGS.
18171   MachineBasicBlock::iterator miI(std::next(SelectItr));
18172   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18173     const MachineInstr& mi = *miI;
18174     if (mi.readsRegister(X86::EFLAGS))
18175       return false;
18176     if (mi.definesRegister(X86::EFLAGS))
18177       break; // Should have kill-flag - update below.
18178   }
18179
18180   // If we hit the end of the block, check whether EFLAGS is live into a
18181   // successor.
18182   if (miI == BB->end()) {
18183     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18184                                           sEnd = BB->succ_end();
18185          sItr != sEnd; ++sItr) {
18186       MachineBasicBlock* succ = *sItr;
18187       if (succ->isLiveIn(X86::EFLAGS))
18188         return false;
18189     }
18190   }
18191
18192   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18193   // out. SelectMI should have a kill flag on EFLAGS.
18194   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18195   return true;
18196 }
18197
18198 MachineBasicBlock *
18199 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18200                                      MachineBasicBlock *BB) const {
18201   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18202   DebugLoc DL = MI->getDebugLoc();
18203
18204   // To "insert" a SELECT_CC instruction, we actually have to insert the
18205   // diamond control-flow pattern.  The incoming instruction knows the
18206   // destination vreg to set, the condition code register to branch on, the
18207   // true/false values to select between, and a branch opcode to use.
18208   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18209   MachineFunction::iterator It = BB;
18210   ++It;
18211
18212   //  thisMBB:
18213   //  ...
18214   //   TrueVal = ...
18215   //   cmpTY ccX, r1, r2
18216   //   bCC copy1MBB
18217   //   fallthrough --> copy0MBB
18218   MachineBasicBlock *thisMBB = BB;
18219   MachineFunction *F = BB->getParent();
18220
18221   // We also lower double CMOVs:
18222   //   (CMOV (CMOV F, T, cc1), T, cc2)
18223   // to two successives branches.  For that, we look for another CMOV as the
18224   // following instruction.
18225   //
18226   // Without this, we would add a PHI between the two jumps, which ends up
18227   // creating a few copies all around. For instance, for
18228   //
18229   //    (sitofp (zext (fcmp une)))
18230   //
18231   // we would generate:
18232   //
18233   //         ucomiss %xmm1, %xmm0
18234   //         movss  <1.0f>, %xmm0
18235   //         movaps  %xmm0, %xmm1
18236   //         jne     .LBB5_2
18237   //         xorps   %xmm1, %xmm1
18238   // .LBB5_2:
18239   //         jp      .LBB5_4
18240   //         movaps  %xmm1, %xmm0
18241   // .LBB5_4:
18242   //         retq
18243   //
18244   // because this custom-inserter would have generated:
18245   //
18246   //   A
18247   //   | \
18248   //   |  B
18249   //   | /
18250   //   C
18251   //   | \
18252   //   |  D
18253   //   | /
18254   //   E
18255   //
18256   // A: X = ...; Y = ...
18257   // B: empty
18258   // C: Z = PHI [X, A], [Y, B]
18259   // D: empty
18260   // E: PHI [X, C], [Z, D]
18261   //
18262   // If we lower both CMOVs in a single step, we can instead generate:
18263   //
18264   //   A
18265   //   | \
18266   //   |  C
18267   //   | /|
18268   //   |/ |
18269   //   |  |
18270   //   |  D
18271   //   | /
18272   //   E
18273   //
18274   // A: X = ...; Y = ...
18275   // D: empty
18276   // E: PHI [X, A], [X, C], [Y, D]
18277   //
18278   // Which, in our sitofp/fcmp example, gives us something like:
18279   //
18280   //         ucomiss %xmm1, %xmm0
18281   //         movss  <1.0f>, %xmm0
18282   //         jne     .LBB5_4
18283   //         jp      .LBB5_4
18284   //         xorps   %xmm0, %xmm0
18285   // .LBB5_4:
18286   //         retq
18287   //
18288   MachineInstr *NextCMOV = nullptr;
18289   MachineBasicBlock::iterator NextMIIt =
18290       std::next(MachineBasicBlock::iterator(MI));
18291   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18292       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18293       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18294     NextCMOV = &*NextMIIt;
18295
18296   MachineBasicBlock *jcc1MBB = nullptr;
18297
18298   // If we have a double CMOV, we lower it to two successive branches to
18299   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18300   if (NextCMOV) {
18301     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18302     F->insert(It, jcc1MBB);
18303     jcc1MBB->addLiveIn(X86::EFLAGS);
18304   }
18305
18306   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18307   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18308   F->insert(It, copy0MBB);
18309   F->insert(It, sinkMBB);
18310
18311   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18312   // live into the sink and copy blocks.
18313   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18314
18315   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18316   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18317       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18318     copy0MBB->addLiveIn(X86::EFLAGS);
18319     sinkMBB->addLiveIn(X86::EFLAGS);
18320   }
18321
18322   // Transfer the remainder of BB and its successor edges to sinkMBB.
18323   sinkMBB->splice(sinkMBB->begin(), BB,
18324                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18325   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18326
18327   // Add the true and fallthrough blocks as its successors.
18328   if (NextCMOV) {
18329     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18330     BB->addSuccessor(jcc1MBB);
18331
18332     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18333     // jump to the sinkMBB.
18334     jcc1MBB->addSuccessor(copy0MBB);
18335     jcc1MBB->addSuccessor(sinkMBB);
18336   } else {
18337     BB->addSuccessor(copy0MBB);
18338   }
18339
18340   // The true block target of the first (or only) branch is always sinkMBB.
18341   BB->addSuccessor(sinkMBB);
18342
18343   // Create the conditional branch instruction.
18344   unsigned Opc =
18345     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18346   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18347
18348   if (NextCMOV) {
18349     unsigned Opc2 = X86::GetCondBranchFromCond(
18350         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18351     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18352   }
18353
18354   //  copy0MBB:
18355   //   %FalseValue = ...
18356   //   # fallthrough to sinkMBB
18357   copy0MBB->addSuccessor(sinkMBB);
18358
18359   //  sinkMBB:
18360   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18361   //  ...
18362   MachineInstrBuilder MIB =
18363       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18364               MI->getOperand(0).getReg())
18365           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18366           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18367
18368   // If we have a double CMOV, the second Jcc provides the same incoming
18369   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18370   if (NextCMOV) {
18371     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18372     // Copy the PHI result to the register defined by the second CMOV.
18373     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18374             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18375         .addReg(MI->getOperand(0).getReg());
18376     NextCMOV->eraseFromParent();
18377   }
18378
18379   MI->eraseFromParent();   // The pseudo instruction is gone now.
18380   return sinkMBB;
18381 }
18382
18383 MachineBasicBlock *
18384 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18385                                         MachineBasicBlock *BB) const {
18386   MachineFunction *MF = BB->getParent();
18387   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18388   DebugLoc DL = MI->getDebugLoc();
18389   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18390
18391   assert(MF->shouldSplitStack());
18392
18393   const bool Is64Bit = Subtarget->is64Bit();
18394   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18395
18396   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18397   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18398
18399   // BB:
18400   //  ... [Till the alloca]
18401   // If stacklet is not large enough, jump to mallocMBB
18402   //
18403   // bumpMBB:
18404   //  Allocate by subtracting from RSP
18405   //  Jump to continueMBB
18406   //
18407   // mallocMBB:
18408   //  Allocate by call to runtime
18409   //
18410   // continueMBB:
18411   //  ...
18412   //  [rest of original BB]
18413   //
18414
18415   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18416   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18417   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18418
18419   MachineRegisterInfo &MRI = MF->getRegInfo();
18420   const TargetRegisterClass *AddrRegClass =
18421     getRegClassFor(getPointerTy());
18422
18423   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18424     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18425     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18426     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18427     sizeVReg = MI->getOperand(1).getReg(),
18428     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18429
18430   MachineFunction::iterator MBBIter = BB;
18431   ++MBBIter;
18432
18433   MF->insert(MBBIter, bumpMBB);
18434   MF->insert(MBBIter, mallocMBB);
18435   MF->insert(MBBIter, continueMBB);
18436
18437   continueMBB->splice(continueMBB->begin(), BB,
18438                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18439   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18440
18441   // Add code to the main basic block to check if the stack limit has been hit,
18442   // and if so, jump to mallocMBB otherwise to bumpMBB.
18443   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18444   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18445     .addReg(tmpSPVReg).addReg(sizeVReg);
18446   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18447     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18448     .addReg(SPLimitVReg);
18449   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18450
18451   // bumpMBB simply decreases the stack pointer, since we know the current
18452   // stacklet has enough space.
18453   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18454     .addReg(SPLimitVReg);
18455   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18456     .addReg(SPLimitVReg);
18457   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18458
18459   // Calls into a routine in libgcc to allocate more space from the heap.
18460   const uint32_t *RegMask =
18461       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18462   if (IsLP64) {
18463     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18464       .addReg(sizeVReg);
18465     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18466       .addExternalSymbol("__morestack_allocate_stack_space")
18467       .addRegMask(RegMask)
18468       .addReg(X86::RDI, RegState::Implicit)
18469       .addReg(X86::RAX, RegState::ImplicitDefine);
18470   } else if (Is64Bit) {
18471     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18472       .addReg(sizeVReg);
18473     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18474       .addExternalSymbol("__morestack_allocate_stack_space")
18475       .addRegMask(RegMask)
18476       .addReg(X86::EDI, RegState::Implicit)
18477       .addReg(X86::EAX, RegState::ImplicitDefine);
18478   } else {
18479     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18480       .addImm(12);
18481     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18482     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18483       .addExternalSymbol("__morestack_allocate_stack_space")
18484       .addRegMask(RegMask)
18485       .addReg(X86::EAX, RegState::ImplicitDefine);
18486   }
18487
18488   if (!Is64Bit)
18489     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18490       .addImm(16);
18491
18492   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18493     .addReg(IsLP64 ? X86::RAX : X86::EAX);
18494   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18495
18496   // Set up the CFG correctly.
18497   BB->addSuccessor(bumpMBB);
18498   BB->addSuccessor(mallocMBB);
18499   mallocMBB->addSuccessor(continueMBB);
18500   bumpMBB->addSuccessor(continueMBB);
18501
18502   // Take care of the PHI nodes.
18503   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18504           MI->getOperand(0).getReg())
18505     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18506     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18507
18508   // Delete the original pseudo instruction.
18509   MI->eraseFromParent();
18510
18511   // And we're done.
18512   return continueMBB;
18513 }
18514
18515 MachineBasicBlock *
18516 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18517                                         MachineBasicBlock *BB) const {
18518   DebugLoc DL = MI->getDebugLoc();
18519
18520   assert(!Subtarget->isTargetMachO());
18521
18522   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18523
18524   MI->eraseFromParent();   // The pseudo instruction is gone now.
18525   return BB;
18526 }
18527
18528 MachineBasicBlock *
18529 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18530                                       MachineBasicBlock *BB) const {
18531   // This is pretty easy.  We're taking the value that we received from
18532   // our load from the relocation, sticking it in either RDI (x86-64)
18533   // or EAX and doing an indirect call.  The return value will then
18534   // be in the normal return register.
18535   MachineFunction *F = BB->getParent();
18536   const X86InstrInfo *TII = Subtarget->getInstrInfo();
18537   DebugLoc DL = MI->getDebugLoc();
18538
18539   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18540   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18541
18542   // Get a register mask for the lowered call.
18543   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18544   // proper register mask.
18545   const uint32_t *RegMask =
18546       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
18547   if (Subtarget->is64Bit()) {
18548     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18549                                       TII->get(X86::MOV64rm), X86::RDI)
18550     .addReg(X86::RIP)
18551     .addImm(0).addReg(0)
18552     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18553                       MI->getOperand(3).getTargetFlags())
18554     .addReg(0);
18555     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18556     addDirectMem(MIB, X86::RDI);
18557     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18558   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18559     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18560                                       TII->get(X86::MOV32rm), X86::EAX)
18561     .addReg(0)
18562     .addImm(0).addReg(0)
18563     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18564                       MI->getOperand(3).getTargetFlags())
18565     .addReg(0);
18566     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18567     addDirectMem(MIB, X86::EAX);
18568     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18569   } else {
18570     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18571                                       TII->get(X86::MOV32rm), X86::EAX)
18572     .addReg(TII->getGlobalBaseReg(F))
18573     .addImm(0).addReg(0)
18574     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18575                       MI->getOperand(3).getTargetFlags())
18576     .addReg(0);
18577     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18578     addDirectMem(MIB, X86::EAX);
18579     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18580   }
18581
18582   MI->eraseFromParent(); // The pseudo instruction is gone now.
18583   return BB;
18584 }
18585
18586 MachineBasicBlock *
18587 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18588                                     MachineBasicBlock *MBB) const {
18589   DebugLoc DL = MI->getDebugLoc();
18590   MachineFunction *MF = MBB->getParent();
18591   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18592   MachineRegisterInfo &MRI = MF->getRegInfo();
18593
18594   const BasicBlock *BB = MBB->getBasicBlock();
18595   MachineFunction::iterator I = MBB;
18596   ++I;
18597
18598   // Memory Reference
18599   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18600   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18601
18602   unsigned DstReg;
18603   unsigned MemOpndSlot = 0;
18604
18605   unsigned CurOp = 0;
18606
18607   DstReg = MI->getOperand(CurOp++).getReg();
18608   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18609   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18610   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18611   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18612
18613   MemOpndSlot = CurOp;
18614
18615   MVT PVT = getPointerTy();
18616   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18617          "Invalid Pointer Size!");
18618
18619   // For v = setjmp(buf), we generate
18620   //
18621   // thisMBB:
18622   //  buf[LabelOffset] = restoreMBB
18623   //  SjLjSetup restoreMBB
18624   //
18625   // mainMBB:
18626   //  v_main = 0
18627   //
18628   // sinkMBB:
18629   //  v = phi(main, restore)
18630   //
18631   // restoreMBB:
18632   //  if base pointer being used, load it from frame
18633   //  v_restore = 1
18634
18635   MachineBasicBlock *thisMBB = MBB;
18636   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18637   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18638   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18639   MF->insert(I, mainMBB);
18640   MF->insert(I, sinkMBB);
18641   MF->push_back(restoreMBB);
18642
18643   MachineInstrBuilder MIB;
18644
18645   // Transfer the remainder of BB and its successor edges to sinkMBB.
18646   sinkMBB->splice(sinkMBB->begin(), MBB,
18647                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18648   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18649
18650   // thisMBB:
18651   unsigned PtrStoreOpc = 0;
18652   unsigned LabelReg = 0;
18653   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18654   Reloc::Model RM = MF->getTarget().getRelocationModel();
18655   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18656                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18657
18658   // Prepare IP either in reg or imm.
18659   if (!UseImmLabel) {
18660     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18661     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18662     LabelReg = MRI.createVirtualRegister(PtrRC);
18663     if (Subtarget->is64Bit()) {
18664       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18665               .addReg(X86::RIP)
18666               .addImm(0)
18667               .addReg(0)
18668               .addMBB(restoreMBB)
18669               .addReg(0);
18670     } else {
18671       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18672       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18673               .addReg(XII->getGlobalBaseReg(MF))
18674               .addImm(0)
18675               .addReg(0)
18676               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18677               .addReg(0);
18678     }
18679   } else
18680     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18681   // Store IP
18682   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18683   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18684     if (i == X86::AddrDisp)
18685       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18686     else
18687       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18688   }
18689   if (!UseImmLabel)
18690     MIB.addReg(LabelReg);
18691   else
18692     MIB.addMBB(restoreMBB);
18693   MIB.setMemRefs(MMOBegin, MMOEnd);
18694   // Setup
18695   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18696           .addMBB(restoreMBB);
18697
18698   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18699   MIB.addRegMask(RegInfo->getNoPreservedMask());
18700   thisMBB->addSuccessor(mainMBB);
18701   thisMBB->addSuccessor(restoreMBB);
18702
18703   // mainMBB:
18704   //  EAX = 0
18705   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18706   mainMBB->addSuccessor(sinkMBB);
18707
18708   // sinkMBB:
18709   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18710           TII->get(X86::PHI), DstReg)
18711     .addReg(mainDstReg).addMBB(mainMBB)
18712     .addReg(restoreDstReg).addMBB(restoreMBB);
18713
18714   // restoreMBB:
18715   if (RegInfo->hasBasePointer(*MF)) {
18716     const bool Uses64BitFramePtr =
18717         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18718     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18719     X86FI->setRestoreBasePointer(MF);
18720     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18721     unsigned BasePtr = RegInfo->getBaseRegister();
18722     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18723     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18724                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
18725       .setMIFlag(MachineInstr::FrameSetup);
18726   }
18727   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18728   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18729   restoreMBB->addSuccessor(sinkMBB);
18730
18731   MI->eraseFromParent();
18732   return sinkMBB;
18733 }
18734
18735 MachineBasicBlock *
18736 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18737                                      MachineBasicBlock *MBB) const {
18738   DebugLoc DL = MI->getDebugLoc();
18739   MachineFunction *MF = MBB->getParent();
18740   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18741   MachineRegisterInfo &MRI = MF->getRegInfo();
18742
18743   // Memory Reference
18744   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18745   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18746
18747   MVT PVT = getPointerTy();
18748   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18749          "Invalid Pointer Size!");
18750
18751   const TargetRegisterClass *RC =
18752     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18753   unsigned Tmp = MRI.createVirtualRegister(RC);
18754   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18755   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18756   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18757   unsigned SP = RegInfo->getStackRegister();
18758
18759   MachineInstrBuilder MIB;
18760
18761   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18762   const int64_t SPOffset = 2 * PVT.getStoreSize();
18763
18764   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18765   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18766
18767   // Reload FP
18768   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18769   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18770     MIB.addOperand(MI->getOperand(i));
18771   MIB.setMemRefs(MMOBegin, MMOEnd);
18772   // Reload IP
18773   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18774   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18775     if (i == X86::AddrDisp)
18776       MIB.addDisp(MI->getOperand(i), LabelOffset);
18777     else
18778       MIB.addOperand(MI->getOperand(i));
18779   }
18780   MIB.setMemRefs(MMOBegin, MMOEnd);
18781   // Reload SP
18782   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18783   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18784     if (i == X86::AddrDisp)
18785       MIB.addDisp(MI->getOperand(i), SPOffset);
18786     else
18787       MIB.addOperand(MI->getOperand(i));
18788   }
18789   MIB.setMemRefs(MMOBegin, MMOEnd);
18790   // Jump
18791   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18792
18793   MI->eraseFromParent();
18794   return MBB;
18795 }
18796
18797 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18798 // accumulator loops. Writing back to the accumulator allows the coalescer
18799 // to remove extra copies in the loop.
18800 MachineBasicBlock *
18801 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18802                                  MachineBasicBlock *MBB) const {
18803   MachineOperand &AddendOp = MI->getOperand(3);
18804
18805   // Bail out early if the addend isn't a register - we can't switch these.
18806   if (!AddendOp.isReg())
18807     return MBB;
18808
18809   MachineFunction &MF = *MBB->getParent();
18810   MachineRegisterInfo &MRI = MF.getRegInfo();
18811
18812   // Check whether the addend is defined by a PHI:
18813   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18814   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18815   if (!AddendDef.isPHI())
18816     return MBB;
18817
18818   // Look for the following pattern:
18819   // loop:
18820   //   %addend = phi [%entry, 0], [%loop, %result]
18821   //   ...
18822   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18823
18824   // Replace with:
18825   //   loop:
18826   //   %addend = phi [%entry, 0], [%loop, %result]
18827   //   ...
18828   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18829
18830   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18831     assert(AddendDef.getOperand(i).isReg());
18832     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18833     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18834     if (&PHISrcInst == MI) {
18835       // Found a matching instruction.
18836       unsigned NewFMAOpc = 0;
18837       switch (MI->getOpcode()) {
18838         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18839         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18840         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18841         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18842         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18843         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18844         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18845         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18846         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18847         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18848         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18849         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18850         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18851         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18852         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18853         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18854         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18855         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18856         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18857         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18858
18859         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18860         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18861         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18862         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18863         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18864         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18865         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18866         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18867         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18868         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18869         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18870         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18871         default: llvm_unreachable("Unrecognized FMA variant.");
18872       }
18873
18874       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18875       MachineInstrBuilder MIB =
18876         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18877         .addOperand(MI->getOperand(0))
18878         .addOperand(MI->getOperand(3))
18879         .addOperand(MI->getOperand(2))
18880         .addOperand(MI->getOperand(1));
18881       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18882       MI->eraseFromParent();
18883     }
18884   }
18885
18886   return MBB;
18887 }
18888
18889 MachineBasicBlock *
18890 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18891                                                MachineBasicBlock *BB) const {
18892   switch (MI->getOpcode()) {
18893   default: llvm_unreachable("Unexpected instr type to insert");
18894   case X86::TAILJMPd64:
18895   case X86::TAILJMPr64:
18896   case X86::TAILJMPm64:
18897   case X86::TAILJMPd64_REX:
18898   case X86::TAILJMPr64_REX:
18899   case X86::TAILJMPm64_REX:
18900     llvm_unreachable("TAILJMP64 would not be touched here.");
18901   case X86::TCRETURNdi64:
18902   case X86::TCRETURNri64:
18903   case X86::TCRETURNmi64:
18904     return BB;
18905   case X86::WIN_ALLOCA:
18906     return EmitLoweredWinAlloca(MI, BB);
18907   case X86::SEG_ALLOCA_32:
18908   case X86::SEG_ALLOCA_64:
18909     return EmitLoweredSegAlloca(MI, BB);
18910   case X86::TLSCall_32:
18911   case X86::TLSCall_64:
18912     return EmitLoweredTLSCall(MI, BB);
18913   case X86::CMOV_GR8:
18914   case X86::CMOV_FR32:
18915   case X86::CMOV_FR64:
18916   case X86::CMOV_V4F32:
18917   case X86::CMOV_V2F64:
18918   case X86::CMOV_V2I64:
18919   case X86::CMOV_V8F32:
18920   case X86::CMOV_V4F64:
18921   case X86::CMOV_V4I64:
18922   case X86::CMOV_V16F32:
18923   case X86::CMOV_V8F64:
18924   case X86::CMOV_V8I64:
18925   case X86::CMOV_GR16:
18926   case X86::CMOV_GR32:
18927   case X86::CMOV_RFP32:
18928   case X86::CMOV_RFP64:
18929   case X86::CMOV_RFP80:
18930     return EmitLoweredSelect(MI, BB);
18931
18932   case X86::FP32_TO_INT16_IN_MEM:
18933   case X86::FP32_TO_INT32_IN_MEM:
18934   case X86::FP32_TO_INT64_IN_MEM:
18935   case X86::FP64_TO_INT16_IN_MEM:
18936   case X86::FP64_TO_INT32_IN_MEM:
18937   case X86::FP64_TO_INT64_IN_MEM:
18938   case X86::FP80_TO_INT16_IN_MEM:
18939   case X86::FP80_TO_INT32_IN_MEM:
18940   case X86::FP80_TO_INT64_IN_MEM: {
18941     MachineFunction *F = BB->getParent();
18942     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18943     DebugLoc DL = MI->getDebugLoc();
18944
18945     // Change the floating point control register to use "round towards zero"
18946     // mode when truncating to an integer value.
18947     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18948     addFrameReference(BuildMI(*BB, MI, DL,
18949                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18950
18951     // Load the old value of the high byte of the control word...
18952     unsigned OldCW =
18953       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18954     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18955                       CWFrameIdx);
18956
18957     // Set the high part to be round to zero...
18958     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18959       .addImm(0xC7F);
18960
18961     // Reload the modified control word now...
18962     addFrameReference(BuildMI(*BB, MI, DL,
18963                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18964
18965     // Restore the memory image of control word to original value
18966     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18967       .addReg(OldCW);
18968
18969     // Get the X86 opcode to use.
18970     unsigned Opc;
18971     switch (MI->getOpcode()) {
18972     default: llvm_unreachable("illegal opcode!");
18973     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18974     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18975     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18976     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18977     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18978     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18979     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18980     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18981     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18982     }
18983
18984     X86AddressMode AM;
18985     MachineOperand &Op = MI->getOperand(0);
18986     if (Op.isReg()) {
18987       AM.BaseType = X86AddressMode::RegBase;
18988       AM.Base.Reg = Op.getReg();
18989     } else {
18990       AM.BaseType = X86AddressMode::FrameIndexBase;
18991       AM.Base.FrameIndex = Op.getIndex();
18992     }
18993     Op = MI->getOperand(1);
18994     if (Op.isImm())
18995       AM.Scale = Op.getImm();
18996     Op = MI->getOperand(2);
18997     if (Op.isImm())
18998       AM.IndexReg = Op.getImm();
18999     Op = MI->getOperand(3);
19000     if (Op.isGlobal()) {
19001       AM.GV = Op.getGlobal();
19002     } else {
19003       AM.Disp = Op.getImm();
19004     }
19005     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19006                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19007
19008     // Reload the original control word now.
19009     addFrameReference(BuildMI(*BB, MI, DL,
19010                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19011
19012     MI->eraseFromParent();   // The pseudo instruction is gone now.
19013     return BB;
19014   }
19015     // String/text processing lowering.
19016   case X86::PCMPISTRM128REG:
19017   case X86::VPCMPISTRM128REG:
19018   case X86::PCMPISTRM128MEM:
19019   case X86::VPCMPISTRM128MEM:
19020   case X86::PCMPESTRM128REG:
19021   case X86::VPCMPESTRM128REG:
19022   case X86::PCMPESTRM128MEM:
19023   case X86::VPCMPESTRM128MEM:
19024     assert(Subtarget->hasSSE42() &&
19025            "Target must have SSE4.2 or AVX features enabled");
19026     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19027
19028   // String/text processing lowering.
19029   case X86::PCMPISTRIREG:
19030   case X86::VPCMPISTRIREG:
19031   case X86::PCMPISTRIMEM:
19032   case X86::VPCMPISTRIMEM:
19033   case X86::PCMPESTRIREG:
19034   case X86::VPCMPESTRIREG:
19035   case X86::PCMPESTRIMEM:
19036   case X86::VPCMPESTRIMEM:
19037     assert(Subtarget->hasSSE42() &&
19038            "Target must have SSE4.2 or AVX features enabled");
19039     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19040
19041   // Thread synchronization.
19042   case X86::MONITOR:
19043     return EmitMonitor(MI, BB, Subtarget);
19044
19045   // xbegin
19046   case X86::XBEGIN:
19047     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19048
19049   case X86::VASTART_SAVE_XMM_REGS:
19050     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19051
19052   case X86::VAARG_64:
19053     return EmitVAARG64WithCustomInserter(MI, BB);
19054
19055   case X86::EH_SjLj_SetJmp32:
19056   case X86::EH_SjLj_SetJmp64:
19057     return emitEHSjLjSetJmp(MI, BB);
19058
19059   case X86::EH_SjLj_LongJmp32:
19060   case X86::EH_SjLj_LongJmp64:
19061     return emitEHSjLjLongJmp(MI, BB);
19062
19063   case TargetOpcode::STATEPOINT:
19064     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19065     // this point in the process.  We diverge later.
19066     return emitPatchPoint(MI, BB);
19067
19068   case TargetOpcode::STACKMAP:
19069   case TargetOpcode::PATCHPOINT:
19070     return emitPatchPoint(MI, BB);
19071
19072   case X86::VFMADDPDr213r:
19073   case X86::VFMADDPSr213r:
19074   case X86::VFMADDSDr213r:
19075   case X86::VFMADDSSr213r:
19076   case X86::VFMSUBPDr213r:
19077   case X86::VFMSUBPSr213r:
19078   case X86::VFMSUBSDr213r:
19079   case X86::VFMSUBSSr213r:
19080   case X86::VFNMADDPDr213r:
19081   case X86::VFNMADDPSr213r:
19082   case X86::VFNMADDSDr213r:
19083   case X86::VFNMADDSSr213r:
19084   case X86::VFNMSUBPDr213r:
19085   case X86::VFNMSUBPSr213r:
19086   case X86::VFNMSUBSDr213r:
19087   case X86::VFNMSUBSSr213r:
19088   case X86::VFMADDSUBPDr213r:
19089   case X86::VFMADDSUBPSr213r:
19090   case X86::VFMSUBADDPDr213r:
19091   case X86::VFMSUBADDPSr213r:
19092   case X86::VFMADDPDr213rY:
19093   case X86::VFMADDPSr213rY:
19094   case X86::VFMSUBPDr213rY:
19095   case X86::VFMSUBPSr213rY:
19096   case X86::VFNMADDPDr213rY:
19097   case X86::VFNMADDPSr213rY:
19098   case X86::VFNMSUBPDr213rY:
19099   case X86::VFNMSUBPSr213rY:
19100   case X86::VFMADDSUBPDr213rY:
19101   case X86::VFMADDSUBPSr213rY:
19102   case X86::VFMSUBADDPDr213rY:
19103   case X86::VFMSUBADDPSr213rY:
19104     return emitFMA3Instr(MI, BB);
19105   }
19106 }
19107
19108 //===----------------------------------------------------------------------===//
19109 //                           X86 Optimization Hooks
19110 //===----------------------------------------------------------------------===//
19111
19112 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19113                                                       APInt &KnownZero,
19114                                                       APInt &KnownOne,
19115                                                       const SelectionDAG &DAG,
19116                                                       unsigned Depth) const {
19117   unsigned BitWidth = KnownZero.getBitWidth();
19118   unsigned Opc = Op.getOpcode();
19119   assert((Opc >= ISD::BUILTIN_OP_END ||
19120           Opc == ISD::INTRINSIC_WO_CHAIN ||
19121           Opc == ISD::INTRINSIC_W_CHAIN ||
19122           Opc == ISD::INTRINSIC_VOID) &&
19123          "Should use MaskedValueIsZero if you don't know whether Op"
19124          " is a target node!");
19125
19126   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19127   switch (Opc) {
19128   default: break;
19129   case X86ISD::ADD:
19130   case X86ISD::SUB:
19131   case X86ISD::ADC:
19132   case X86ISD::SBB:
19133   case X86ISD::SMUL:
19134   case X86ISD::UMUL:
19135   case X86ISD::INC:
19136   case X86ISD::DEC:
19137   case X86ISD::OR:
19138   case X86ISD::XOR:
19139   case X86ISD::AND:
19140     // These nodes' second result is a boolean.
19141     if (Op.getResNo() == 0)
19142       break;
19143     // Fallthrough
19144   case X86ISD::SETCC:
19145     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19146     break;
19147   case ISD::INTRINSIC_WO_CHAIN: {
19148     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19149     unsigned NumLoBits = 0;
19150     switch (IntId) {
19151     default: break;
19152     case Intrinsic::x86_sse_movmsk_ps:
19153     case Intrinsic::x86_avx_movmsk_ps_256:
19154     case Intrinsic::x86_sse2_movmsk_pd:
19155     case Intrinsic::x86_avx_movmsk_pd_256:
19156     case Intrinsic::x86_mmx_pmovmskb:
19157     case Intrinsic::x86_sse2_pmovmskb_128:
19158     case Intrinsic::x86_avx2_pmovmskb: {
19159       // High bits of movmskp{s|d}, pmovmskb are known zero.
19160       switch (IntId) {
19161         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19162         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19163         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19164         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19165         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19166         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19167         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19168         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19169       }
19170       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19171       break;
19172     }
19173     }
19174     break;
19175   }
19176   }
19177 }
19178
19179 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19180   SDValue Op,
19181   const SelectionDAG &,
19182   unsigned Depth) const {
19183   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19184   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19185     return Op.getValueType().getScalarType().getSizeInBits();
19186
19187   // Fallback case.
19188   return 1;
19189 }
19190
19191 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19192 /// node is a GlobalAddress + offset.
19193 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19194                                        const GlobalValue* &GA,
19195                                        int64_t &Offset) const {
19196   if (N->getOpcode() == X86ISD::Wrapper) {
19197     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19198       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19199       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19200       return true;
19201     }
19202   }
19203   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19204 }
19205
19206 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19207 /// same as extracting the high 128-bit part of 256-bit vector and then
19208 /// inserting the result into the low part of a new 256-bit vector
19209 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19210   EVT VT = SVOp->getValueType(0);
19211   unsigned NumElems = VT.getVectorNumElements();
19212
19213   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19214   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19215     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19216         SVOp->getMaskElt(j) >= 0)
19217       return false;
19218
19219   return true;
19220 }
19221
19222 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19223 /// same as extracting the low 128-bit part of 256-bit vector and then
19224 /// inserting the result into the high part of a new 256-bit vector
19225 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19226   EVT VT = SVOp->getValueType(0);
19227   unsigned NumElems = VT.getVectorNumElements();
19228
19229   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19230   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19231     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19232         SVOp->getMaskElt(j) >= 0)
19233       return false;
19234
19235   return true;
19236 }
19237
19238 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19239 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19240                                         TargetLowering::DAGCombinerInfo &DCI,
19241                                         const X86Subtarget* Subtarget) {
19242   SDLoc dl(N);
19243   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19244   SDValue V1 = SVOp->getOperand(0);
19245   SDValue V2 = SVOp->getOperand(1);
19246   EVT VT = SVOp->getValueType(0);
19247   unsigned NumElems = VT.getVectorNumElements();
19248
19249   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19250       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19251     //
19252     //                   0,0,0,...
19253     //                      |
19254     //    V      UNDEF    BUILD_VECTOR    UNDEF
19255     //     \      /           \           /
19256     //  CONCAT_VECTOR         CONCAT_VECTOR
19257     //         \                  /
19258     //          \                /
19259     //          RESULT: V + zero extended
19260     //
19261     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19262         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19263         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19264       return SDValue();
19265
19266     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19267       return SDValue();
19268
19269     // To match the shuffle mask, the first half of the mask should
19270     // be exactly the first vector, and all the rest a splat with the
19271     // first element of the second one.
19272     for (unsigned i = 0; i != NumElems/2; ++i)
19273       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19274           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19275         return SDValue();
19276
19277     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19278     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19279       if (Ld->hasNUsesOfValue(1, 0)) {
19280         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19281         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19282         SDValue ResNode =
19283           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19284                                   Ld->getMemoryVT(),
19285                                   Ld->getPointerInfo(),
19286                                   Ld->getAlignment(),
19287                                   false/*isVolatile*/, true/*ReadMem*/,
19288                                   false/*WriteMem*/);
19289
19290         // Make sure the newly-created LOAD is in the same position as Ld in
19291         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19292         // and update uses of Ld's output chain to use the TokenFactor.
19293         if (Ld->hasAnyUseOfValue(1)) {
19294           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19295                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19296           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19297           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19298                                  SDValue(ResNode.getNode(), 1));
19299         }
19300
19301         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19302       }
19303     }
19304
19305     // Emit a zeroed vector and insert the desired subvector on its
19306     // first half.
19307     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19308     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19309     return DCI.CombineTo(N, InsV);
19310   }
19311
19312   //===--------------------------------------------------------------------===//
19313   // Combine some shuffles into subvector extracts and inserts:
19314   //
19315
19316   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19317   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19318     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19319     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19320     return DCI.CombineTo(N, InsV);
19321   }
19322
19323   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19324   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19325     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19326     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19327     return DCI.CombineTo(N, InsV);
19328   }
19329
19330   return SDValue();
19331 }
19332
19333 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19334 /// possible.
19335 ///
19336 /// This is the leaf of the recursive combinine below. When we have found some
19337 /// chain of single-use x86 shuffle instructions and accumulated the combined
19338 /// shuffle mask represented by them, this will try to pattern match that mask
19339 /// into either a single instruction if there is a special purpose instruction
19340 /// for this operation, or into a PSHUFB instruction which is a fully general
19341 /// instruction but should only be used to replace chains over a certain depth.
19342 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19343                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19344                                    TargetLowering::DAGCombinerInfo &DCI,
19345                                    const X86Subtarget *Subtarget) {
19346   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19347
19348   // Find the operand that enters the chain. Note that multiple uses are OK
19349   // here, we're not going to remove the operand we find.
19350   SDValue Input = Op.getOperand(0);
19351   while (Input.getOpcode() == ISD::BITCAST)
19352     Input = Input.getOperand(0);
19353
19354   MVT VT = Input.getSimpleValueType();
19355   MVT RootVT = Root.getSimpleValueType();
19356   SDLoc DL(Root);
19357
19358   // Just remove no-op shuffle masks.
19359   if (Mask.size() == 1) {
19360     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19361                   /*AddTo*/ true);
19362     return true;
19363   }
19364
19365   // Use the float domain if the operand type is a floating point type.
19366   bool FloatDomain = VT.isFloatingPoint();
19367
19368   // For floating point shuffles, we don't have free copies in the shuffle
19369   // instructions or the ability to load as part of the instruction, so
19370   // canonicalize their shuffles to UNPCK or MOV variants.
19371   //
19372   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19373   // vectors because it can have a load folded into it that UNPCK cannot. This
19374   // doesn't preclude something switching to the shorter encoding post-RA.
19375   //
19376   // FIXME: Should teach these routines about AVX vector widths.
19377   if (FloatDomain && VT.getSizeInBits() == 128) {
19378     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19379       bool Lo = Mask.equals({0, 0});
19380       unsigned Shuffle;
19381       MVT ShuffleVT;
19382       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19383       // is no slower than UNPCKLPD but has the option to fold the input operand
19384       // into even an unaligned memory load.
19385       if (Lo && Subtarget->hasSSE3()) {
19386         Shuffle = X86ISD::MOVDDUP;
19387         ShuffleVT = MVT::v2f64;
19388       } else {
19389         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19390         // than the UNPCK variants.
19391         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19392         ShuffleVT = MVT::v4f32;
19393       }
19394       if (Depth == 1 && Root->getOpcode() == Shuffle)
19395         return false; // Nothing to do!
19396       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19397       DCI.AddToWorklist(Op.getNode());
19398       if (Shuffle == X86ISD::MOVDDUP)
19399         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19400       else
19401         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19402       DCI.AddToWorklist(Op.getNode());
19403       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19404                     /*AddTo*/ true);
19405       return true;
19406     }
19407     if (Subtarget->hasSSE3() &&
19408         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19409       bool Lo = Mask.equals({0, 0, 2, 2});
19410       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19411       MVT ShuffleVT = MVT::v4f32;
19412       if (Depth == 1 && Root->getOpcode() == Shuffle)
19413         return false; // Nothing to do!
19414       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19415       DCI.AddToWorklist(Op.getNode());
19416       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19417       DCI.AddToWorklist(Op.getNode());
19418       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19419                     /*AddTo*/ true);
19420       return true;
19421     }
19422     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19423       bool Lo = Mask.equals({0, 0, 1, 1});
19424       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19425       MVT ShuffleVT = MVT::v4f32;
19426       if (Depth == 1 && Root->getOpcode() == Shuffle)
19427         return false; // Nothing to do!
19428       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19429       DCI.AddToWorklist(Op.getNode());
19430       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19431       DCI.AddToWorklist(Op.getNode());
19432       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19433                     /*AddTo*/ true);
19434       return true;
19435     }
19436   }
19437
19438   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19439   // variants as none of these have single-instruction variants that are
19440   // superior to the UNPCK formulation.
19441   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19442       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19443        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19444        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19445        Mask.equals(
19446            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19447     bool Lo = Mask[0] == 0;
19448     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19449     if (Depth == 1 && Root->getOpcode() == Shuffle)
19450       return false; // Nothing to do!
19451     MVT ShuffleVT;
19452     switch (Mask.size()) {
19453     case 8:
19454       ShuffleVT = MVT::v8i16;
19455       break;
19456     case 16:
19457       ShuffleVT = MVT::v16i8;
19458       break;
19459     default:
19460       llvm_unreachable("Impossible mask size!");
19461     };
19462     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19463     DCI.AddToWorklist(Op.getNode());
19464     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19465     DCI.AddToWorklist(Op.getNode());
19466     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19467                   /*AddTo*/ true);
19468     return true;
19469   }
19470
19471   // Don't try to re-form single instruction chains under any circumstances now
19472   // that we've done encoding canonicalization for them.
19473   if (Depth < 2)
19474     return false;
19475
19476   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19477   // can replace them with a single PSHUFB instruction profitably. Intel's
19478   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19479   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19480   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19481     SmallVector<SDValue, 16> PSHUFBMask;
19482     int NumBytes = VT.getSizeInBits() / 8;
19483     int Ratio = NumBytes / Mask.size();
19484     for (int i = 0; i < NumBytes; ++i) {
19485       if (Mask[i / Ratio] == SM_SentinelUndef) {
19486         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19487         continue;
19488       }
19489       int M = Mask[i / Ratio] != SM_SentinelZero
19490                   ? Ratio * Mask[i / Ratio] + i % Ratio
19491                   : 255;
19492       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19493     }
19494     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19495     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19496     DCI.AddToWorklist(Op.getNode());
19497     SDValue PSHUFBMaskOp =
19498         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19499     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19500     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19501     DCI.AddToWorklist(Op.getNode());
19502     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19503                   /*AddTo*/ true);
19504     return true;
19505   }
19506
19507   // Failed to find any combines.
19508   return false;
19509 }
19510
19511 /// \brief Fully generic combining of x86 shuffle instructions.
19512 ///
19513 /// This should be the last combine run over the x86 shuffle instructions. Once
19514 /// they have been fully optimized, this will recursively consider all chains
19515 /// of single-use shuffle instructions, build a generic model of the cumulative
19516 /// shuffle operation, and check for simpler instructions which implement this
19517 /// operation. We use this primarily for two purposes:
19518 ///
19519 /// 1) Collapse generic shuffles to specialized single instructions when
19520 ///    equivalent. In most cases, this is just an encoding size win, but
19521 ///    sometimes we will collapse multiple generic shuffles into a single
19522 ///    special-purpose shuffle.
19523 /// 2) Look for sequences of shuffle instructions with 3 or more total
19524 ///    instructions, and replace them with the slightly more expensive SSSE3
19525 ///    PSHUFB instruction if available. We do this as the last combining step
19526 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19527 ///    a suitable short sequence of other instructions. The PHUFB will either
19528 ///    use a register or have to read from memory and so is slightly (but only
19529 ///    slightly) more expensive than the other shuffle instructions.
19530 ///
19531 /// Because this is inherently a quadratic operation (for each shuffle in
19532 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19533 /// This should never be an issue in practice as the shuffle lowering doesn't
19534 /// produce sequences of more than 8 instructions.
19535 ///
19536 /// FIXME: We will currently miss some cases where the redundant shuffling
19537 /// would simplify under the threshold for PSHUFB formation because of
19538 /// combine-ordering. To fix this, we should do the redundant instruction
19539 /// combining in this recursive walk.
19540 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19541                                           ArrayRef<int> RootMask,
19542                                           int Depth, bool HasPSHUFB,
19543                                           SelectionDAG &DAG,
19544                                           TargetLowering::DAGCombinerInfo &DCI,
19545                                           const X86Subtarget *Subtarget) {
19546   // Bound the depth of our recursive combine because this is ultimately
19547   // quadratic in nature.
19548   if (Depth > 8)
19549     return false;
19550
19551   // Directly rip through bitcasts to find the underlying operand.
19552   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19553     Op = Op.getOperand(0);
19554
19555   MVT VT = Op.getSimpleValueType();
19556   if (!VT.isVector())
19557     return false; // Bail if we hit a non-vector.
19558
19559   assert(Root.getSimpleValueType().isVector() &&
19560          "Shuffles operate on vector types!");
19561   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19562          "Can only combine shuffles of the same vector register size.");
19563
19564   if (!isTargetShuffle(Op.getOpcode()))
19565     return false;
19566   SmallVector<int, 16> OpMask;
19567   bool IsUnary;
19568   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19569   // We only can combine unary shuffles which we can decode the mask for.
19570   if (!HaveMask || !IsUnary)
19571     return false;
19572
19573   assert(VT.getVectorNumElements() == OpMask.size() &&
19574          "Different mask size from vector size!");
19575   assert(((RootMask.size() > OpMask.size() &&
19576            RootMask.size() % OpMask.size() == 0) ||
19577           (OpMask.size() > RootMask.size() &&
19578            OpMask.size() % RootMask.size() == 0) ||
19579           OpMask.size() == RootMask.size()) &&
19580          "The smaller number of elements must divide the larger.");
19581   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19582   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19583   assert(((RootRatio == 1 && OpRatio == 1) ||
19584           (RootRatio == 1) != (OpRatio == 1)) &&
19585          "Must not have a ratio for both incoming and op masks!");
19586
19587   SmallVector<int, 16> Mask;
19588   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19589
19590   // Merge this shuffle operation's mask into our accumulated mask. Note that
19591   // this shuffle's mask will be the first applied to the input, followed by the
19592   // root mask to get us all the way to the root value arrangement. The reason
19593   // for this order is that we are recursing up the operation chain.
19594   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19595     int RootIdx = i / RootRatio;
19596     if (RootMask[RootIdx] < 0) {
19597       // This is a zero or undef lane, we're done.
19598       Mask.push_back(RootMask[RootIdx]);
19599       continue;
19600     }
19601
19602     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19603     int OpIdx = RootMaskedIdx / OpRatio;
19604     if (OpMask[OpIdx] < 0) {
19605       // The incoming lanes are zero or undef, it doesn't matter which ones we
19606       // are using.
19607       Mask.push_back(OpMask[OpIdx]);
19608       continue;
19609     }
19610
19611     // Ok, we have non-zero lanes, map them through.
19612     Mask.push_back(OpMask[OpIdx] * OpRatio +
19613                    RootMaskedIdx % OpRatio);
19614   }
19615
19616   // See if we can recurse into the operand to combine more things.
19617   switch (Op.getOpcode()) {
19618     case X86ISD::PSHUFB:
19619       HasPSHUFB = true;
19620     case X86ISD::PSHUFD:
19621     case X86ISD::PSHUFHW:
19622     case X86ISD::PSHUFLW:
19623       if (Op.getOperand(0).hasOneUse() &&
19624           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19625                                         HasPSHUFB, DAG, DCI, Subtarget))
19626         return true;
19627       break;
19628
19629     case X86ISD::UNPCKL:
19630     case X86ISD::UNPCKH:
19631       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19632       // We can't check for single use, we have to check that this shuffle is the only user.
19633       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19634           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19635                                         HasPSHUFB, DAG, DCI, Subtarget))
19636           return true;
19637       break;
19638   }
19639
19640   // Minor canonicalization of the accumulated shuffle mask to make it easier
19641   // to match below. All this does is detect masks with squential pairs of
19642   // elements, and shrink them to the half-width mask. It does this in a loop
19643   // so it will reduce the size of the mask to the minimal width mask which
19644   // performs an equivalent shuffle.
19645   SmallVector<int, 16> WidenedMask;
19646   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19647     Mask = std::move(WidenedMask);
19648     WidenedMask.clear();
19649   }
19650
19651   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19652                                 Subtarget);
19653 }
19654
19655 /// \brief Get the PSHUF-style mask from PSHUF node.
19656 ///
19657 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19658 /// PSHUF-style masks that can be reused with such instructions.
19659 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19660   MVT VT = N.getSimpleValueType();
19661   SmallVector<int, 4> Mask;
19662   bool IsUnary;
19663   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19664   (void)HaveMask;
19665   assert(HaveMask);
19666
19667   // If we have more than 128-bits, only the low 128-bits of shuffle mask
19668   // matter. Check that the upper masks are repeats and remove them.
19669   if (VT.getSizeInBits() > 128) {
19670     int LaneElts = 128 / VT.getScalarSizeInBits();
19671 #ifndef NDEBUG
19672     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19673       for (int j = 0; j < LaneElts; ++j)
19674         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19675                "Mask doesn't repeat in high 128-bit lanes!");
19676 #endif
19677     Mask.resize(LaneElts);
19678   }
19679
19680   switch (N.getOpcode()) {
19681   case X86ISD::PSHUFD:
19682     return Mask;
19683   case X86ISD::PSHUFLW:
19684     Mask.resize(4);
19685     return Mask;
19686   case X86ISD::PSHUFHW:
19687     Mask.erase(Mask.begin(), Mask.begin() + 4);
19688     for (int &M : Mask)
19689       M -= 4;
19690     return Mask;
19691   default:
19692     llvm_unreachable("No valid shuffle instruction found!");
19693   }
19694 }
19695
19696 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19697 ///
19698 /// We walk up the chain and look for a combinable shuffle, skipping over
19699 /// shuffles that we could hoist this shuffle's transformation past without
19700 /// altering anything.
19701 static SDValue
19702 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19703                              SelectionDAG &DAG,
19704                              TargetLowering::DAGCombinerInfo &DCI) {
19705   assert(N.getOpcode() == X86ISD::PSHUFD &&
19706          "Called with something other than an x86 128-bit half shuffle!");
19707   SDLoc DL(N);
19708
19709   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19710   // of the shuffles in the chain so that we can form a fresh chain to replace
19711   // this one.
19712   SmallVector<SDValue, 8> Chain;
19713   SDValue V = N.getOperand(0);
19714   for (; V.hasOneUse(); V = V.getOperand(0)) {
19715     switch (V.getOpcode()) {
19716     default:
19717       return SDValue(); // Nothing combined!
19718
19719     case ISD::BITCAST:
19720       // Skip bitcasts as we always know the type for the target specific
19721       // instructions.
19722       continue;
19723
19724     case X86ISD::PSHUFD:
19725       // Found another dword shuffle.
19726       break;
19727
19728     case X86ISD::PSHUFLW:
19729       // Check that the low words (being shuffled) are the identity in the
19730       // dword shuffle, and the high words are self-contained.
19731       if (Mask[0] != 0 || Mask[1] != 1 ||
19732           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19733         return SDValue();
19734
19735       Chain.push_back(V);
19736       continue;
19737
19738     case X86ISD::PSHUFHW:
19739       // Check that the high words (being shuffled) are the identity in the
19740       // dword shuffle, and the low words are self-contained.
19741       if (Mask[2] != 2 || Mask[3] != 3 ||
19742           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19743         return SDValue();
19744
19745       Chain.push_back(V);
19746       continue;
19747
19748     case X86ISD::UNPCKL:
19749     case X86ISD::UNPCKH:
19750       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19751       // shuffle into a preceding word shuffle.
19752       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19753           V.getSimpleValueType().getScalarType() != MVT::i16)
19754         return SDValue();
19755
19756       // Search for a half-shuffle which we can combine with.
19757       unsigned CombineOp =
19758           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19759       if (V.getOperand(0) != V.getOperand(1) ||
19760           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19761         return SDValue();
19762       Chain.push_back(V);
19763       V = V.getOperand(0);
19764       do {
19765         switch (V.getOpcode()) {
19766         default:
19767           return SDValue(); // Nothing to combine.
19768
19769         case X86ISD::PSHUFLW:
19770         case X86ISD::PSHUFHW:
19771           if (V.getOpcode() == CombineOp)
19772             break;
19773
19774           Chain.push_back(V);
19775
19776           // Fallthrough!
19777         case ISD::BITCAST:
19778           V = V.getOperand(0);
19779           continue;
19780         }
19781         break;
19782       } while (V.hasOneUse());
19783       break;
19784     }
19785     // Break out of the loop if we break out of the switch.
19786     break;
19787   }
19788
19789   if (!V.hasOneUse())
19790     // We fell out of the loop without finding a viable combining instruction.
19791     return SDValue();
19792
19793   // Merge this node's mask and our incoming mask.
19794   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19795   for (int &M : Mask)
19796     M = VMask[M];
19797   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19798                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19799
19800   // Rebuild the chain around this new shuffle.
19801   while (!Chain.empty()) {
19802     SDValue W = Chain.pop_back_val();
19803
19804     if (V.getValueType() != W.getOperand(0).getValueType())
19805       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19806
19807     switch (W.getOpcode()) {
19808     default:
19809       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19810
19811     case X86ISD::UNPCKL:
19812     case X86ISD::UNPCKH:
19813       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19814       break;
19815
19816     case X86ISD::PSHUFD:
19817     case X86ISD::PSHUFLW:
19818     case X86ISD::PSHUFHW:
19819       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19820       break;
19821     }
19822   }
19823   if (V.getValueType() != N.getValueType())
19824     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19825
19826   // Return the new chain to replace N.
19827   return V;
19828 }
19829
19830 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19831 ///
19832 /// We walk up the chain, skipping shuffles of the other half and looking
19833 /// through shuffles which switch halves trying to find a shuffle of the same
19834 /// pair of dwords.
19835 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19836                                         SelectionDAG &DAG,
19837                                         TargetLowering::DAGCombinerInfo &DCI) {
19838   assert(
19839       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19840       "Called with something other than an x86 128-bit half shuffle!");
19841   SDLoc DL(N);
19842   unsigned CombineOpcode = N.getOpcode();
19843
19844   // Walk up a single-use chain looking for a combinable shuffle.
19845   SDValue V = N.getOperand(0);
19846   for (; V.hasOneUse(); V = V.getOperand(0)) {
19847     switch (V.getOpcode()) {
19848     default:
19849       return false; // Nothing combined!
19850
19851     case ISD::BITCAST:
19852       // Skip bitcasts as we always know the type for the target specific
19853       // instructions.
19854       continue;
19855
19856     case X86ISD::PSHUFLW:
19857     case X86ISD::PSHUFHW:
19858       if (V.getOpcode() == CombineOpcode)
19859         break;
19860
19861       // Other-half shuffles are no-ops.
19862       continue;
19863     }
19864     // Break out of the loop if we break out of the switch.
19865     break;
19866   }
19867
19868   if (!V.hasOneUse())
19869     // We fell out of the loop without finding a viable combining instruction.
19870     return false;
19871
19872   // Combine away the bottom node as its shuffle will be accumulated into
19873   // a preceding shuffle.
19874   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19875
19876   // Record the old value.
19877   SDValue Old = V;
19878
19879   // Merge this node's mask and our incoming mask (adjusted to account for all
19880   // the pshufd instructions encountered).
19881   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19882   for (int &M : Mask)
19883     M = VMask[M];
19884   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19885                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19886
19887   // Check that the shuffles didn't cancel each other out. If not, we need to
19888   // combine to the new one.
19889   if (Old != V)
19890     // Replace the combinable shuffle with the combined one, updating all users
19891     // so that we re-evaluate the chain here.
19892     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19893
19894   return true;
19895 }
19896
19897 /// \brief Try to combine x86 target specific shuffles.
19898 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19899                                            TargetLowering::DAGCombinerInfo &DCI,
19900                                            const X86Subtarget *Subtarget) {
19901   SDLoc DL(N);
19902   MVT VT = N.getSimpleValueType();
19903   SmallVector<int, 4> Mask;
19904
19905   switch (N.getOpcode()) {
19906   case X86ISD::PSHUFD:
19907   case X86ISD::PSHUFLW:
19908   case X86ISD::PSHUFHW:
19909     Mask = getPSHUFShuffleMask(N);
19910     assert(Mask.size() == 4);
19911     break;
19912   default:
19913     return SDValue();
19914   }
19915
19916   // Nuke no-op shuffles that show up after combining.
19917   if (isNoopShuffleMask(Mask))
19918     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19919
19920   // Look for simplifications involving one or two shuffle instructions.
19921   SDValue V = N.getOperand(0);
19922   switch (N.getOpcode()) {
19923   default:
19924     break;
19925   case X86ISD::PSHUFLW:
19926   case X86ISD::PSHUFHW:
19927     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
19928
19929     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19930       return SDValue(); // We combined away this shuffle, so we're done.
19931
19932     // See if this reduces to a PSHUFD which is no more expensive and can
19933     // combine with more operations. Note that it has to at least flip the
19934     // dwords as otherwise it would have been removed as a no-op.
19935     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
19936       int DMask[] = {0, 1, 2, 3};
19937       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19938       DMask[DOffset + 0] = DOffset + 1;
19939       DMask[DOffset + 1] = DOffset + 0;
19940       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
19941       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
19942       DCI.AddToWorklist(V.getNode());
19943       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
19944                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19945       DCI.AddToWorklist(V.getNode());
19946       return DAG.getNode(ISD::BITCAST, DL, VT, V);
19947     }
19948
19949     // Look for shuffle patterns which can be implemented as a single unpack.
19950     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19951     // only works when we have a PSHUFD followed by two half-shuffles.
19952     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19953         (V.getOpcode() == X86ISD::PSHUFLW ||
19954          V.getOpcode() == X86ISD::PSHUFHW) &&
19955         V.getOpcode() != N.getOpcode() &&
19956         V.hasOneUse()) {
19957       SDValue D = V.getOperand(0);
19958       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19959         D = D.getOperand(0);
19960       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19961         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19962         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19963         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19964         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19965         int WordMask[8];
19966         for (int i = 0; i < 4; ++i) {
19967           WordMask[i + NOffset] = Mask[i] + NOffset;
19968           WordMask[i + VOffset] = VMask[i] + VOffset;
19969         }
19970         // Map the word mask through the DWord mask.
19971         int MappedMask[8];
19972         for (int i = 0; i < 8; ++i)
19973           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19974         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19975             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
19976           // We can replace all three shuffles with an unpack.
19977           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
19978           DCI.AddToWorklist(V.getNode());
19979           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19980                                                 : X86ISD::UNPCKH,
19981                              DL, VT, V, V);
19982         }
19983       }
19984     }
19985
19986     break;
19987
19988   case X86ISD::PSHUFD:
19989     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19990       return NewN;
19991
19992     break;
19993   }
19994
19995   return SDValue();
19996 }
19997
19998 /// \brief Try to combine a shuffle into a target-specific add-sub node.
19999 ///
20000 /// We combine this directly on the abstract vector shuffle nodes so it is
20001 /// easier to generically match. We also insert dummy vector shuffle nodes for
20002 /// the operands which explicitly discard the lanes which are unused by this
20003 /// operation to try to flow through the rest of the combiner the fact that
20004 /// they're unused.
20005 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20006   SDLoc DL(N);
20007   EVT VT = N->getValueType(0);
20008
20009   // We only handle target-independent shuffles.
20010   // FIXME: It would be easy and harmless to use the target shuffle mask
20011   // extraction tool to support more.
20012   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20013     return SDValue();
20014
20015   auto *SVN = cast<ShuffleVectorSDNode>(N);
20016   ArrayRef<int> Mask = SVN->getMask();
20017   SDValue V1 = N->getOperand(0);
20018   SDValue V2 = N->getOperand(1);
20019
20020   // We require the first shuffle operand to be the SUB node, and the second to
20021   // be the ADD node.
20022   // FIXME: We should support the commuted patterns.
20023   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20024     return SDValue();
20025
20026   // If there are other uses of these operations we can't fold them.
20027   if (!V1->hasOneUse() || !V2->hasOneUse())
20028     return SDValue();
20029
20030   // Ensure that both operations have the same operands. Note that we can
20031   // commute the FADD operands.
20032   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20033   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20034       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20035     return SDValue();
20036
20037   // We're looking for blends between FADD and FSUB nodes. We insist on these
20038   // nodes being lined up in a specific expected pattern.
20039   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20040         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20041         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20042     return SDValue();
20043
20044   // Only specific types are legal at this point, assert so we notice if and
20045   // when these change.
20046   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20047           VT == MVT::v4f64) &&
20048          "Unknown vector type encountered!");
20049
20050   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20051 }
20052
20053 /// PerformShuffleCombine - Performs several different shuffle combines.
20054 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20055                                      TargetLowering::DAGCombinerInfo &DCI,
20056                                      const X86Subtarget *Subtarget) {
20057   SDLoc dl(N);
20058   SDValue N0 = N->getOperand(0);
20059   SDValue N1 = N->getOperand(1);
20060   EVT VT = N->getValueType(0);
20061
20062   // Don't create instructions with illegal types after legalize types has run.
20063   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20064   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20065     return SDValue();
20066
20067   // If we have legalized the vector types, look for blends of FADD and FSUB
20068   // nodes that we can fuse into an ADDSUB node.
20069   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20070     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20071       return AddSub;
20072
20073   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20074   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20075       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20076     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20077
20078   // During Type Legalization, when promoting illegal vector types,
20079   // the backend might introduce new shuffle dag nodes and bitcasts.
20080   //
20081   // This code performs the following transformation:
20082   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20083   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20084   //
20085   // We do this only if both the bitcast and the BINOP dag nodes have
20086   // one use. Also, perform this transformation only if the new binary
20087   // operation is legal. This is to avoid introducing dag nodes that
20088   // potentially need to be further expanded (or custom lowered) into a
20089   // less optimal sequence of dag nodes.
20090   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20091       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20092       N0.getOpcode() == ISD::BITCAST) {
20093     SDValue BC0 = N0.getOperand(0);
20094     EVT SVT = BC0.getValueType();
20095     unsigned Opcode = BC0.getOpcode();
20096     unsigned NumElts = VT.getVectorNumElements();
20097
20098     if (BC0.hasOneUse() && SVT.isVector() &&
20099         SVT.getVectorNumElements() * 2 == NumElts &&
20100         TLI.isOperationLegal(Opcode, VT)) {
20101       bool CanFold = false;
20102       switch (Opcode) {
20103       default : break;
20104       case ISD::ADD :
20105       case ISD::FADD :
20106       case ISD::SUB :
20107       case ISD::FSUB :
20108       case ISD::MUL :
20109       case ISD::FMUL :
20110         CanFold = true;
20111       }
20112
20113       unsigned SVTNumElts = SVT.getVectorNumElements();
20114       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20115       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20116         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20117       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20118         CanFold = SVOp->getMaskElt(i) < 0;
20119
20120       if (CanFold) {
20121         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20122         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20123         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20124         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20125       }
20126     }
20127   }
20128
20129   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20130   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20131   // consecutive, non-overlapping, and in the right order.
20132   SmallVector<SDValue, 16> Elts;
20133   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20134     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20135
20136   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20137   if (LD.getNode())
20138     return LD;
20139
20140   if (isTargetShuffle(N->getOpcode())) {
20141     SDValue Shuffle =
20142         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20143     if (Shuffle.getNode())
20144       return Shuffle;
20145
20146     // Try recursively combining arbitrary sequences of x86 shuffle
20147     // instructions into higher-order shuffles. We do this after combining
20148     // specific PSHUF instruction sequences into their minimal form so that we
20149     // can evaluate how many specialized shuffle instructions are involved in
20150     // a particular chain.
20151     SmallVector<int, 1> NonceMask; // Just a placeholder.
20152     NonceMask.push_back(0);
20153     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20154                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20155                                       DCI, Subtarget))
20156       return SDValue(); // This routine will use CombineTo to replace N.
20157   }
20158
20159   return SDValue();
20160 }
20161
20162 /// PerformTruncateCombine - Converts truncate operation to
20163 /// a sequence of vector shuffle operations.
20164 /// It is possible when we truncate 256-bit vector to 128-bit vector
20165 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20166                                       TargetLowering::DAGCombinerInfo &DCI,
20167                                       const X86Subtarget *Subtarget)  {
20168   return SDValue();
20169 }
20170
20171 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20172 /// specific shuffle of a load can be folded into a single element load.
20173 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20174 /// shuffles have been custom lowered so we need to handle those here.
20175 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20176                                          TargetLowering::DAGCombinerInfo &DCI) {
20177   if (DCI.isBeforeLegalizeOps())
20178     return SDValue();
20179
20180   SDValue InVec = N->getOperand(0);
20181   SDValue EltNo = N->getOperand(1);
20182
20183   if (!isa<ConstantSDNode>(EltNo))
20184     return SDValue();
20185
20186   EVT OriginalVT = InVec.getValueType();
20187
20188   if (InVec.getOpcode() == ISD::BITCAST) {
20189     // Don't duplicate a load with other uses.
20190     if (!InVec.hasOneUse())
20191       return SDValue();
20192     EVT BCVT = InVec.getOperand(0).getValueType();
20193     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20194       return SDValue();
20195     InVec = InVec.getOperand(0);
20196   }
20197
20198   EVT CurrentVT = InVec.getValueType();
20199
20200   if (!isTargetShuffle(InVec.getOpcode()))
20201     return SDValue();
20202
20203   // Don't duplicate a load with other uses.
20204   if (!InVec.hasOneUse())
20205     return SDValue();
20206
20207   SmallVector<int, 16> ShuffleMask;
20208   bool UnaryShuffle;
20209   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20210                             ShuffleMask, UnaryShuffle))
20211     return SDValue();
20212
20213   // Select the input vector, guarding against out of range extract vector.
20214   unsigned NumElems = CurrentVT.getVectorNumElements();
20215   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20216   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20217   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20218                                          : InVec.getOperand(1);
20219
20220   // If inputs to shuffle are the same for both ops, then allow 2 uses
20221   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20222                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20223
20224   if (LdNode.getOpcode() == ISD::BITCAST) {
20225     // Don't duplicate a load with other uses.
20226     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20227       return SDValue();
20228
20229     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20230     LdNode = LdNode.getOperand(0);
20231   }
20232
20233   if (!ISD::isNormalLoad(LdNode.getNode()))
20234     return SDValue();
20235
20236   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20237
20238   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20239     return SDValue();
20240
20241   EVT EltVT = N->getValueType(0);
20242   // If there's a bitcast before the shuffle, check if the load type and
20243   // alignment is valid.
20244   unsigned Align = LN0->getAlignment();
20245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20246   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20247       EltVT.getTypeForEVT(*DAG.getContext()));
20248
20249   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20250     return SDValue();
20251
20252   // All checks match so transform back to vector_shuffle so that DAG combiner
20253   // can finish the job
20254   SDLoc dl(N);
20255
20256   // Create shuffle node taking into account the case that its a unary shuffle
20257   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20258                                    : InVec.getOperand(1);
20259   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20260                                  InVec.getOperand(0), Shuffle,
20261                                  &ShuffleMask[0]);
20262   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20263   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20264                      EltNo);
20265 }
20266
20267 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20268 /// special and don't usually play with other vector types, it's better to
20269 /// handle them early to be sure we emit efficient code by avoiding
20270 /// store-load conversions.
20271 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20272   if (N->getValueType(0) != MVT::x86mmx ||
20273       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20274       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20275     return SDValue();
20276
20277   SDValue V = N->getOperand(0);
20278   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20279   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20280     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20281                        N->getValueType(0), V.getOperand(0));
20282
20283   return SDValue();
20284 }
20285
20286 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20287 /// generation and convert it from being a bunch of shuffles and extracts
20288 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20289 /// storing the value and loading scalars back, while for x64 we should
20290 /// use 64-bit extracts and shifts.
20291 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20292                                          TargetLowering::DAGCombinerInfo &DCI) {
20293   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20294   if (NewOp.getNode())
20295     return NewOp;
20296
20297   SDValue InputVector = N->getOperand(0);
20298
20299   // Detect mmx to i32 conversion through a v2i32 elt extract.
20300   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20301       N->getValueType(0) == MVT::i32 &&
20302       InputVector.getValueType() == MVT::v2i32) {
20303
20304     // The bitcast source is a direct mmx result.
20305     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20306     if (MMXSrc.getValueType() == MVT::x86mmx)
20307       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20308                          N->getValueType(0),
20309                          InputVector.getNode()->getOperand(0));
20310
20311     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20312     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20313     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20314         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20315         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20316         MMXSrcOp.getValueType() == MVT::v1i64 &&
20317         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20318       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20319                          N->getValueType(0),
20320                          MMXSrcOp.getOperand(0));
20321   }
20322
20323   // Only operate on vectors of 4 elements, where the alternative shuffling
20324   // gets to be more expensive.
20325   if (InputVector.getValueType() != MVT::v4i32)
20326     return SDValue();
20327
20328   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20329   // single use which is a sign-extend or zero-extend, and all elements are
20330   // used.
20331   SmallVector<SDNode *, 4> Uses;
20332   unsigned ExtractedElements = 0;
20333   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20334        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20335     if (UI.getUse().getResNo() != InputVector.getResNo())
20336       return SDValue();
20337
20338     SDNode *Extract = *UI;
20339     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20340       return SDValue();
20341
20342     if (Extract->getValueType(0) != MVT::i32)
20343       return SDValue();
20344     if (!Extract->hasOneUse())
20345       return SDValue();
20346     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20347         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20348       return SDValue();
20349     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20350       return SDValue();
20351
20352     // Record which element was extracted.
20353     ExtractedElements |=
20354       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20355
20356     Uses.push_back(Extract);
20357   }
20358
20359   // If not all the elements were used, this may not be worthwhile.
20360   if (ExtractedElements != 15)
20361     return SDValue();
20362
20363   // Ok, we've now decided to do the transformation.
20364   // If 64-bit shifts are legal, use the extract-shift sequence,
20365   // otherwise bounce the vector off the cache.
20366   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20367   SDValue Vals[4];
20368   SDLoc dl(InputVector);
20369
20370   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20371     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20372     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20373     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20374       DAG.getConstant(0, VecIdxTy));
20375     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20376       DAG.getConstant(1, VecIdxTy));
20377
20378     SDValue ShAmt = DAG.getConstant(32,
20379       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20380     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20381     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20382       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20383     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20384     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20385       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20386   } else {
20387     // Store the value to a temporary stack slot.
20388     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20389     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20390       MachinePointerInfo(), false, false, 0);
20391
20392     EVT ElementType = InputVector.getValueType().getVectorElementType();
20393     unsigned EltSize = ElementType.getSizeInBits() / 8;
20394
20395     // Replace each use (extract) with a load of the appropriate element.
20396     for (unsigned i = 0; i < 4; ++i) {
20397       uint64_t Offset = EltSize * i;
20398       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20399
20400       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20401                                        StackPtr, OffsetVal);
20402
20403       // Load the scalar.
20404       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20405                             ScalarAddr, MachinePointerInfo(),
20406                             false, false, false, 0);
20407
20408     }
20409   }
20410
20411   // Replace the extracts
20412   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20413     UE = Uses.end(); UI != UE; ++UI) {
20414     SDNode *Extract = *UI;
20415
20416     SDValue Idx = Extract->getOperand(1);
20417     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20418     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20419   }
20420
20421   // The replacement was made in place; don't return anything.
20422   return SDValue();
20423 }
20424
20425 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20426 static std::pair<unsigned, bool>
20427 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20428                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20429   if (!VT.isVector())
20430     return std::make_pair(0, false);
20431
20432   bool NeedSplit = false;
20433   switch (VT.getSimpleVT().SimpleTy) {
20434   default: return std::make_pair(0, false);
20435   case MVT::v4i64:
20436   case MVT::v2i64:
20437     if (!Subtarget->hasVLX())
20438       return std::make_pair(0, false);
20439     break;
20440   case MVT::v64i8:
20441   case MVT::v32i16:
20442     if (!Subtarget->hasBWI())
20443       return std::make_pair(0, false);
20444     break;
20445   case MVT::v16i32:
20446   case MVT::v8i64:
20447     if (!Subtarget->hasAVX512())
20448       return std::make_pair(0, false);
20449     break;
20450   case MVT::v32i8:
20451   case MVT::v16i16:
20452   case MVT::v8i32:
20453     if (!Subtarget->hasAVX2())
20454       NeedSplit = true;
20455     if (!Subtarget->hasAVX())
20456       return std::make_pair(0, false);
20457     break;
20458   case MVT::v16i8:
20459   case MVT::v8i16:
20460   case MVT::v4i32:
20461     if (!Subtarget->hasSSE2())
20462       return std::make_pair(0, false);
20463   }
20464
20465   // SSE2 has only a small subset of the operations.
20466   bool hasUnsigned = Subtarget->hasSSE41() ||
20467                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20468   bool hasSigned = Subtarget->hasSSE41() ||
20469                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20470
20471   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20472
20473   unsigned Opc = 0;
20474   // Check for x CC y ? x : y.
20475   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20476       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20477     switch (CC) {
20478     default: break;
20479     case ISD::SETULT:
20480     case ISD::SETULE:
20481       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20482     case ISD::SETUGT:
20483     case ISD::SETUGE:
20484       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20485     case ISD::SETLT:
20486     case ISD::SETLE:
20487       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20488     case ISD::SETGT:
20489     case ISD::SETGE:
20490       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20491     }
20492   // Check for x CC y ? y : x -- a min/max with reversed arms.
20493   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20494              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20495     switch (CC) {
20496     default: break;
20497     case ISD::SETULT:
20498     case ISD::SETULE:
20499       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20500     case ISD::SETUGT:
20501     case ISD::SETUGE:
20502       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20503     case ISD::SETLT:
20504     case ISD::SETLE:
20505       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20506     case ISD::SETGT:
20507     case ISD::SETGE:
20508       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20509     }
20510   }
20511
20512   return std::make_pair(Opc, NeedSplit);
20513 }
20514
20515 static SDValue
20516 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20517                                       const X86Subtarget *Subtarget) {
20518   SDLoc dl(N);
20519   SDValue Cond = N->getOperand(0);
20520   SDValue LHS = N->getOperand(1);
20521   SDValue RHS = N->getOperand(2);
20522
20523   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20524     SDValue CondSrc = Cond->getOperand(0);
20525     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20526       Cond = CondSrc->getOperand(0);
20527   }
20528
20529   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20530     return SDValue();
20531
20532   // A vselect where all conditions and data are constants can be optimized into
20533   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20534   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20535       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20536     return SDValue();
20537
20538   unsigned MaskValue = 0;
20539   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20540     return SDValue();
20541
20542   MVT VT = N->getSimpleValueType(0);
20543   unsigned NumElems = VT.getVectorNumElements();
20544   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20545   for (unsigned i = 0; i < NumElems; ++i) {
20546     // Be sure we emit undef where we can.
20547     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20548       ShuffleMask[i] = -1;
20549     else
20550       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20551   }
20552
20553   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20554   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20555     return SDValue();
20556   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20557 }
20558
20559 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20560 /// nodes.
20561 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20562                                     TargetLowering::DAGCombinerInfo &DCI,
20563                                     const X86Subtarget *Subtarget) {
20564   SDLoc DL(N);
20565   SDValue Cond = N->getOperand(0);
20566   // Get the LHS/RHS of the select.
20567   SDValue LHS = N->getOperand(1);
20568   SDValue RHS = N->getOperand(2);
20569   EVT VT = LHS.getValueType();
20570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20571
20572   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20573   // instructions match the semantics of the common C idiom x<y?x:y but not
20574   // x<=y?x:y, because of how they handle negative zero (which can be
20575   // ignored in unsafe-math mode).
20576   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20577   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20578       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20579       (Subtarget->hasSSE2() ||
20580        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20581     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20582
20583     unsigned Opcode = 0;
20584     // Check for x CC y ? x : y.
20585     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20586         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20587       switch (CC) {
20588       default: break;
20589       case ISD::SETULT:
20590         // Converting this to a min would handle NaNs incorrectly, and swapping
20591         // the operands would cause it to handle comparisons between positive
20592         // and negative zero incorrectly.
20593         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20594           if (!DAG.getTarget().Options.UnsafeFPMath &&
20595               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20596             break;
20597           std::swap(LHS, RHS);
20598         }
20599         Opcode = X86ISD::FMIN;
20600         break;
20601       case ISD::SETOLE:
20602         // Converting this to a min would handle comparisons between positive
20603         // and negative zero incorrectly.
20604         if (!DAG.getTarget().Options.UnsafeFPMath &&
20605             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20606           break;
20607         Opcode = X86ISD::FMIN;
20608         break;
20609       case ISD::SETULE:
20610         // Converting this to a min would handle both negative zeros and NaNs
20611         // incorrectly, but we can swap the operands to fix both.
20612         std::swap(LHS, RHS);
20613       case ISD::SETOLT:
20614       case ISD::SETLT:
20615       case ISD::SETLE:
20616         Opcode = X86ISD::FMIN;
20617         break;
20618
20619       case ISD::SETOGE:
20620         // Converting this to a max would handle comparisons between positive
20621         // and negative zero incorrectly.
20622         if (!DAG.getTarget().Options.UnsafeFPMath &&
20623             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20624           break;
20625         Opcode = X86ISD::FMAX;
20626         break;
20627       case ISD::SETUGT:
20628         // Converting this to a max would handle NaNs incorrectly, and swapping
20629         // the operands would cause it to handle comparisons between positive
20630         // and negative zero incorrectly.
20631         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20632           if (!DAG.getTarget().Options.UnsafeFPMath &&
20633               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20634             break;
20635           std::swap(LHS, RHS);
20636         }
20637         Opcode = X86ISD::FMAX;
20638         break;
20639       case ISD::SETUGE:
20640         // Converting this to a max would handle both negative zeros and NaNs
20641         // incorrectly, but we can swap the operands to fix both.
20642         std::swap(LHS, RHS);
20643       case ISD::SETOGT:
20644       case ISD::SETGT:
20645       case ISD::SETGE:
20646         Opcode = X86ISD::FMAX;
20647         break;
20648       }
20649     // Check for x CC y ? y : x -- a min/max with reversed arms.
20650     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20651                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20652       switch (CC) {
20653       default: break;
20654       case ISD::SETOGE:
20655         // Converting this to a min would handle comparisons between positive
20656         // and negative zero incorrectly, and swapping the operands would
20657         // cause it to handle NaNs incorrectly.
20658         if (!DAG.getTarget().Options.UnsafeFPMath &&
20659             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20660           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20661             break;
20662           std::swap(LHS, RHS);
20663         }
20664         Opcode = X86ISD::FMIN;
20665         break;
20666       case ISD::SETUGT:
20667         // Converting this to a min would handle NaNs incorrectly.
20668         if (!DAG.getTarget().Options.UnsafeFPMath &&
20669             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20670           break;
20671         Opcode = X86ISD::FMIN;
20672         break;
20673       case ISD::SETUGE:
20674         // Converting this to a min would handle both negative zeros and NaNs
20675         // incorrectly, but we can swap the operands to fix both.
20676         std::swap(LHS, RHS);
20677       case ISD::SETOGT:
20678       case ISD::SETGT:
20679       case ISD::SETGE:
20680         Opcode = X86ISD::FMIN;
20681         break;
20682
20683       case ISD::SETULT:
20684         // Converting this to a max would handle NaNs incorrectly.
20685         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20686           break;
20687         Opcode = X86ISD::FMAX;
20688         break;
20689       case ISD::SETOLE:
20690         // Converting this to a max would handle comparisons between positive
20691         // and negative zero incorrectly, and swapping the operands would
20692         // cause it to handle NaNs incorrectly.
20693         if (!DAG.getTarget().Options.UnsafeFPMath &&
20694             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20695           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20696             break;
20697           std::swap(LHS, RHS);
20698         }
20699         Opcode = X86ISD::FMAX;
20700         break;
20701       case ISD::SETULE:
20702         // Converting this to a max would handle both negative zeros and NaNs
20703         // incorrectly, but we can swap the operands to fix both.
20704         std::swap(LHS, RHS);
20705       case ISD::SETOLT:
20706       case ISD::SETLT:
20707       case ISD::SETLE:
20708         Opcode = X86ISD::FMAX;
20709         break;
20710       }
20711     }
20712
20713     if (Opcode)
20714       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20715   }
20716
20717   EVT CondVT = Cond.getValueType();
20718   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20719       CondVT.getVectorElementType() == MVT::i1) {
20720     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20721     // lowering on KNL. In this case we convert it to
20722     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20723     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20724     // Since SKX these selects have a proper lowering.
20725     EVT OpVT = LHS.getValueType();
20726     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20727         (OpVT.getVectorElementType() == MVT::i8 ||
20728          OpVT.getVectorElementType() == MVT::i16) &&
20729         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20730       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20731       DCI.AddToWorklist(Cond.getNode());
20732       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20733     }
20734   }
20735   // If this is a select between two integer constants, try to do some
20736   // optimizations.
20737   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20738     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20739       // Don't do this for crazy integer types.
20740       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20741         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20742         // so that TrueC (the true value) is larger than FalseC.
20743         bool NeedsCondInvert = false;
20744
20745         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20746             // Efficiently invertible.
20747             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20748              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20749               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20750           NeedsCondInvert = true;
20751           std::swap(TrueC, FalseC);
20752         }
20753
20754         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20755         if (FalseC->getAPIntValue() == 0 &&
20756             TrueC->getAPIntValue().isPowerOf2()) {
20757           if (NeedsCondInvert) // Invert the condition if needed.
20758             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20759                                DAG.getConstant(1, Cond.getValueType()));
20760
20761           // Zero extend the condition if needed.
20762           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20763
20764           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20765           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20766                              DAG.getConstant(ShAmt, MVT::i8));
20767         }
20768
20769         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20770         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20771           if (NeedsCondInvert) // Invert the condition if needed.
20772             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20773                                DAG.getConstant(1, Cond.getValueType()));
20774
20775           // Zero extend the condition if needed.
20776           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20777                              FalseC->getValueType(0), Cond);
20778           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20779                              SDValue(FalseC, 0));
20780         }
20781
20782         // Optimize cases that will turn into an LEA instruction.  This requires
20783         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20784         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20785           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20786           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20787
20788           bool isFastMultiplier = false;
20789           if (Diff < 10) {
20790             switch ((unsigned char)Diff) {
20791               default: break;
20792               case 1:  // result = add base, cond
20793               case 2:  // result = lea base(    , cond*2)
20794               case 3:  // result = lea base(cond, cond*2)
20795               case 4:  // result = lea base(    , cond*4)
20796               case 5:  // result = lea base(cond, cond*4)
20797               case 8:  // result = lea base(    , cond*8)
20798               case 9:  // result = lea base(cond, cond*8)
20799                 isFastMultiplier = true;
20800                 break;
20801             }
20802           }
20803
20804           if (isFastMultiplier) {
20805             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20806             if (NeedsCondInvert) // Invert the condition if needed.
20807               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20808                                  DAG.getConstant(1, Cond.getValueType()));
20809
20810             // Zero extend the condition if needed.
20811             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20812                                Cond);
20813             // Scale the condition by the difference.
20814             if (Diff != 1)
20815               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20816                                  DAG.getConstant(Diff, Cond.getValueType()));
20817
20818             // Add the base if non-zero.
20819             if (FalseC->getAPIntValue() != 0)
20820               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20821                                  SDValue(FalseC, 0));
20822             return Cond;
20823           }
20824         }
20825       }
20826   }
20827
20828   // Canonicalize max and min:
20829   // (x > y) ? x : y -> (x >= y) ? x : y
20830   // (x < y) ? x : y -> (x <= y) ? x : y
20831   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20832   // the need for an extra compare
20833   // against zero. e.g.
20834   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20835   // subl   %esi, %edi
20836   // testl  %edi, %edi
20837   // movl   $0, %eax
20838   // cmovgl %edi, %eax
20839   // =>
20840   // xorl   %eax, %eax
20841   // subl   %esi, $edi
20842   // cmovsl %eax, %edi
20843   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20844       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20845       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20846     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20847     switch (CC) {
20848     default: break;
20849     case ISD::SETLT:
20850     case ISD::SETGT: {
20851       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20852       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20853                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20854       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20855     }
20856     }
20857   }
20858
20859   // Early exit check
20860   if (!TLI.isTypeLegal(VT))
20861     return SDValue();
20862
20863   // Match VSELECTs into subs with unsigned saturation.
20864   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20865       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20866       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20867        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20868     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20869
20870     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20871     // left side invert the predicate to simplify logic below.
20872     SDValue Other;
20873     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20874       Other = RHS;
20875       CC = ISD::getSetCCInverse(CC, true);
20876     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20877       Other = LHS;
20878     }
20879
20880     if (Other.getNode() && Other->getNumOperands() == 2 &&
20881         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20882       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20883       SDValue CondRHS = Cond->getOperand(1);
20884
20885       // Look for a general sub with unsigned saturation first.
20886       // x >= y ? x-y : 0 --> subus x, y
20887       // x >  y ? x-y : 0 --> subus x, y
20888       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20889           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20890         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20891
20892       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20893         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20894           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20895             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20896               // If the RHS is a constant we have to reverse the const
20897               // canonicalization.
20898               // x > C-1 ? x+-C : 0 --> subus x, C
20899               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20900                   CondRHSConst->getAPIntValue() ==
20901                       (-OpRHSConst->getAPIntValue() - 1))
20902                 return DAG.getNode(
20903                     X86ISD::SUBUS, DL, VT, OpLHS,
20904                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20905
20906           // Another special case: If C was a sign bit, the sub has been
20907           // canonicalized into a xor.
20908           // FIXME: Would it be better to use computeKnownBits to determine
20909           //        whether it's safe to decanonicalize the xor?
20910           // x s< 0 ? x^C : 0 --> subus x, C
20911           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20912               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20913               OpRHSConst->getAPIntValue().isSignBit())
20914             // Note that we have to rebuild the RHS constant here to ensure we
20915             // don't rely on particular values of undef lanes.
20916             return DAG.getNode(
20917                 X86ISD::SUBUS, DL, VT, OpLHS,
20918                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20919         }
20920     }
20921   }
20922
20923   // Try to match a min/max vector operation.
20924   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20925     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20926     unsigned Opc = ret.first;
20927     bool NeedSplit = ret.second;
20928
20929     if (Opc && NeedSplit) {
20930       unsigned NumElems = VT.getVectorNumElements();
20931       // Extract the LHS vectors
20932       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20933       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20934
20935       // Extract the RHS vectors
20936       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20937       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20938
20939       // Create min/max for each subvector
20940       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20941       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20942
20943       // Merge the result
20944       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20945     } else if (Opc)
20946       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20947   }
20948
20949   // Simplify vector selection if condition value type matches vselect
20950   // operand type
20951   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
20952     assert(Cond.getValueType().isVector() &&
20953            "vector select expects a vector selector!");
20954
20955     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20956     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20957
20958     // Try invert the condition if true value is not all 1s and false value
20959     // is not all 0s.
20960     if (!TValIsAllOnes && !FValIsAllZeros &&
20961         // Check if the selector will be produced by CMPP*/PCMP*
20962         Cond.getOpcode() == ISD::SETCC &&
20963         // Check if SETCC has already been promoted
20964         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
20965       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20966       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20967
20968       if (TValIsAllZeros || FValIsAllOnes) {
20969         SDValue CC = Cond.getOperand(2);
20970         ISD::CondCode NewCC =
20971           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20972                                Cond.getOperand(0).getValueType().isInteger());
20973         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20974         std::swap(LHS, RHS);
20975         TValIsAllOnes = FValIsAllOnes;
20976         FValIsAllZeros = TValIsAllZeros;
20977       }
20978     }
20979
20980     if (TValIsAllOnes || FValIsAllZeros) {
20981       SDValue Ret;
20982
20983       if (TValIsAllOnes && FValIsAllZeros)
20984         Ret = Cond;
20985       else if (TValIsAllOnes)
20986         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20987                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20988       else if (FValIsAllZeros)
20989         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20990                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20991
20992       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20993     }
20994   }
20995
20996   // We should generate an X86ISD::BLENDI from a vselect if its argument
20997   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20998   // constants. This specific pattern gets generated when we split a
20999   // selector for a 512 bit vector in a machine without AVX512 (but with
21000   // 256-bit vectors), during legalization:
21001   //
21002   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21003   //
21004   // Iff we find this pattern and the build_vectors are built from
21005   // constants, we translate the vselect into a shuffle_vector that we
21006   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21007   if ((N->getOpcode() == ISD::VSELECT ||
21008        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21009       !DCI.isBeforeLegalize()) {
21010     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21011     if (Shuffle.getNode())
21012       return Shuffle;
21013   }
21014
21015   // If this is a *dynamic* select (non-constant condition) and we can match
21016   // this node with one of the variable blend instructions, restructure the
21017   // condition so that the blends can use the high bit of each element and use
21018   // SimplifyDemandedBits to simplify the condition operand.
21019   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21020       !DCI.isBeforeLegalize() &&
21021       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21022     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21023
21024     // Don't optimize vector selects that map to mask-registers.
21025     if (BitWidth == 1)
21026       return SDValue();
21027
21028     // We can only handle the cases where VSELECT is directly legal on the
21029     // subtarget. We custom lower VSELECT nodes with constant conditions and
21030     // this makes it hard to see whether a dynamic VSELECT will correctly
21031     // lower, so we both check the operation's status and explicitly handle the
21032     // cases where a *dynamic* blend will fail even though a constant-condition
21033     // blend could be custom lowered.
21034     // FIXME: We should find a better way to handle this class of problems.
21035     // Potentially, we should combine constant-condition vselect nodes
21036     // pre-legalization into shuffles and not mark as many types as custom
21037     // lowered.
21038     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21039       return SDValue();
21040     // FIXME: We don't support i16-element blends currently. We could and
21041     // should support them by making *all* the bits in the condition be set
21042     // rather than just the high bit and using an i8-element blend.
21043     if (VT.getScalarType() == MVT::i16)
21044       return SDValue();
21045     // Dynamic blending was only available from SSE4.1 onward.
21046     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21047       return SDValue();
21048     // Byte blends are only available in AVX2
21049     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21050         !Subtarget->hasAVX2())
21051       return SDValue();
21052
21053     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21054     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21055
21056     APInt KnownZero, KnownOne;
21057     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21058                                           DCI.isBeforeLegalizeOps());
21059     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21060         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21061                                  TLO)) {
21062       // If we changed the computation somewhere in the DAG, this change
21063       // will affect all users of Cond.
21064       // Make sure it is fine and update all the nodes so that we do not
21065       // use the generic VSELECT anymore. Otherwise, we may perform
21066       // wrong optimizations as we messed up with the actual expectation
21067       // for the vector boolean values.
21068       if (Cond != TLO.Old) {
21069         // Check all uses of that condition operand to check whether it will be
21070         // consumed by non-BLEND instructions, which may depend on all bits are
21071         // set properly.
21072         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21073              I != E; ++I)
21074           if (I->getOpcode() != ISD::VSELECT)
21075             // TODO: Add other opcodes eventually lowered into BLEND.
21076             return SDValue();
21077
21078         // Update all the users of the condition, before committing the change,
21079         // so that the VSELECT optimizations that expect the correct vector
21080         // boolean value will not be triggered.
21081         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21082              I != E; ++I)
21083           DAG.ReplaceAllUsesOfValueWith(
21084               SDValue(*I, 0),
21085               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21086                           Cond, I->getOperand(1), I->getOperand(2)));
21087         DCI.CommitTargetLoweringOpt(TLO);
21088         return SDValue();
21089       }
21090       // At this point, only Cond is changed. Change the condition
21091       // just for N to keep the opportunity to optimize all other
21092       // users their own way.
21093       DAG.ReplaceAllUsesOfValueWith(
21094           SDValue(N, 0),
21095           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21096                       TLO.New, N->getOperand(1), N->getOperand(2)));
21097       return SDValue();
21098     }
21099   }
21100
21101   return SDValue();
21102 }
21103
21104 // Check whether a boolean test is testing a boolean value generated by
21105 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21106 // code.
21107 //
21108 // Simplify the following patterns:
21109 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21110 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21111 // to (Op EFLAGS Cond)
21112 //
21113 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21114 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21115 // to (Op EFLAGS !Cond)
21116 //
21117 // where Op could be BRCOND or CMOV.
21118 //
21119 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21120   // Quit if not CMP and SUB with its value result used.
21121   if (Cmp.getOpcode() != X86ISD::CMP &&
21122       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21123       return SDValue();
21124
21125   // Quit if not used as a boolean value.
21126   if (CC != X86::COND_E && CC != X86::COND_NE)
21127     return SDValue();
21128
21129   // Check CMP operands. One of them should be 0 or 1 and the other should be
21130   // an SetCC or extended from it.
21131   SDValue Op1 = Cmp.getOperand(0);
21132   SDValue Op2 = Cmp.getOperand(1);
21133
21134   SDValue SetCC;
21135   const ConstantSDNode* C = nullptr;
21136   bool needOppositeCond = (CC == X86::COND_E);
21137   bool checkAgainstTrue = false; // Is it a comparison against 1?
21138
21139   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21140     SetCC = Op2;
21141   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21142     SetCC = Op1;
21143   else // Quit if all operands are not constants.
21144     return SDValue();
21145
21146   if (C->getZExtValue() == 1) {
21147     needOppositeCond = !needOppositeCond;
21148     checkAgainstTrue = true;
21149   } else if (C->getZExtValue() != 0)
21150     // Quit if the constant is neither 0 or 1.
21151     return SDValue();
21152
21153   bool truncatedToBoolWithAnd = false;
21154   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21155   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21156          SetCC.getOpcode() == ISD::TRUNCATE ||
21157          SetCC.getOpcode() == ISD::AND) {
21158     if (SetCC.getOpcode() == ISD::AND) {
21159       int OpIdx = -1;
21160       ConstantSDNode *CS;
21161       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21162           CS->getZExtValue() == 1)
21163         OpIdx = 1;
21164       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21165           CS->getZExtValue() == 1)
21166         OpIdx = 0;
21167       if (OpIdx == -1)
21168         break;
21169       SetCC = SetCC.getOperand(OpIdx);
21170       truncatedToBoolWithAnd = true;
21171     } else
21172       SetCC = SetCC.getOperand(0);
21173   }
21174
21175   switch (SetCC.getOpcode()) {
21176   case X86ISD::SETCC_CARRY:
21177     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21178     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21179     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21180     // truncated to i1 using 'and'.
21181     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21182       break;
21183     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21184            "Invalid use of SETCC_CARRY!");
21185     // FALL THROUGH
21186   case X86ISD::SETCC:
21187     // Set the condition code or opposite one if necessary.
21188     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21189     if (needOppositeCond)
21190       CC = X86::GetOppositeBranchCondition(CC);
21191     return SetCC.getOperand(1);
21192   case X86ISD::CMOV: {
21193     // Check whether false/true value has canonical one, i.e. 0 or 1.
21194     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21195     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21196     // Quit if true value is not a constant.
21197     if (!TVal)
21198       return SDValue();
21199     // Quit if false value is not a constant.
21200     if (!FVal) {
21201       SDValue Op = SetCC.getOperand(0);
21202       // Skip 'zext' or 'trunc' node.
21203       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21204           Op.getOpcode() == ISD::TRUNCATE)
21205         Op = Op.getOperand(0);
21206       // A special case for rdrand/rdseed, where 0 is set if false cond is
21207       // found.
21208       if ((Op.getOpcode() != X86ISD::RDRAND &&
21209            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21210         return SDValue();
21211     }
21212     // Quit if false value is not the constant 0 or 1.
21213     bool FValIsFalse = true;
21214     if (FVal && FVal->getZExtValue() != 0) {
21215       if (FVal->getZExtValue() != 1)
21216         return SDValue();
21217       // If FVal is 1, opposite cond is needed.
21218       needOppositeCond = !needOppositeCond;
21219       FValIsFalse = false;
21220     }
21221     // Quit if TVal is not the constant opposite of FVal.
21222     if (FValIsFalse && TVal->getZExtValue() != 1)
21223       return SDValue();
21224     if (!FValIsFalse && TVal->getZExtValue() != 0)
21225       return SDValue();
21226     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21227     if (needOppositeCond)
21228       CC = X86::GetOppositeBranchCondition(CC);
21229     return SetCC.getOperand(3);
21230   }
21231   }
21232
21233   return SDValue();
21234 }
21235
21236 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21237 /// Match:
21238 ///   (X86or (X86setcc) (X86setcc))
21239 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21240 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21241                                            X86::CondCode &CC1, SDValue &Flags,
21242                                            bool &isAnd) {
21243   if (Cond->getOpcode() == X86ISD::CMP) {
21244     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21245     if (!CondOp1C || !CondOp1C->isNullValue())
21246       return false;
21247
21248     Cond = Cond->getOperand(0);
21249   }
21250
21251   isAnd = false;
21252
21253   SDValue SetCC0, SetCC1;
21254   switch (Cond->getOpcode()) {
21255   default: return false;
21256   case ISD::AND:
21257   case X86ISD::AND:
21258     isAnd = true;
21259     // fallthru
21260   case ISD::OR:
21261   case X86ISD::OR:
21262     SetCC0 = Cond->getOperand(0);
21263     SetCC1 = Cond->getOperand(1);
21264     break;
21265   };
21266
21267   // Make sure we have SETCC nodes, using the same flags value.
21268   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21269       SetCC1.getOpcode() != X86ISD::SETCC ||
21270       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21271     return false;
21272
21273   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21274   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21275   Flags = SetCC0->getOperand(1);
21276   return true;
21277 }
21278
21279 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21280 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21281                                   TargetLowering::DAGCombinerInfo &DCI,
21282                                   const X86Subtarget *Subtarget) {
21283   SDLoc DL(N);
21284
21285   // If the flag operand isn't dead, don't touch this CMOV.
21286   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21287     return SDValue();
21288
21289   SDValue FalseOp = N->getOperand(0);
21290   SDValue TrueOp = N->getOperand(1);
21291   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21292   SDValue Cond = N->getOperand(3);
21293
21294   if (CC == X86::COND_E || CC == X86::COND_NE) {
21295     switch (Cond.getOpcode()) {
21296     default: break;
21297     case X86ISD::BSR:
21298     case X86ISD::BSF:
21299       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21300       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21301         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21302     }
21303   }
21304
21305   SDValue Flags;
21306
21307   Flags = checkBoolTestSetCCCombine(Cond, CC);
21308   if (Flags.getNode() &&
21309       // Extra check as FCMOV only supports a subset of X86 cond.
21310       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21311     SDValue Ops[] = { FalseOp, TrueOp,
21312                       DAG.getConstant(CC, MVT::i8), Flags };
21313     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21314   }
21315
21316   // If this is a select between two integer constants, try to do some
21317   // optimizations.  Note that the operands are ordered the opposite of SELECT
21318   // operands.
21319   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21320     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21321       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21322       // larger than FalseC (the false value).
21323       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21324         CC = X86::GetOppositeBranchCondition(CC);
21325         std::swap(TrueC, FalseC);
21326         std::swap(TrueOp, FalseOp);
21327       }
21328
21329       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21330       // This is efficient for any integer data type (including i8/i16) and
21331       // shift amount.
21332       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21333         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21334                            DAG.getConstant(CC, MVT::i8), Cond);
21335
21336         // Zero extend the condition if needed.
21337         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21338
21339         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21340         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21341                            DAG.getConstant(ShAmt, MVT::i8));
21342         if (N->getNumValues() == 2)  // Dead flag value?
21343           return DCI.CombineTo(N, Cond, SDValue());
21344         return Cond;
21345       }
21346
21347       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21348       // for any integer data type, including i8/i16.
21349       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21350         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21351                            DAG.getConstant(CC, MVT::i8), Cond);
21352
21353         // Zero extend the condition if needed.
21354         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21355                            FalseC->getValueType(0), Cond);
21356         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21357                            SDValue(FalseC, 0));
21358
21359         if (N->getNumValues() == 2)  // Dead flag value?
21360           return DCI.CombineTo(N, Cond, SDValue());
21361         return Cond;
21362       }
21363
21364       // Optimize cases that will turn into an LEA instruction.  This requires
21365       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21366       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21367         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21368         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21369
21370         bool isFastMultiplier = false;
21371         if (Diff < 10) {
21372           switch ((unsigned char)Diff) {
21373           default: break;
21374           case 1:  // result = add base, cond
21375           case 2:  // result = lea base(    , cond*2)
21376           case 3:  // result = lea base(cond, cond*2)
21377           case 4:  // result = lea base(    , cond*4)
21378           case 5:  // result = lea base(cond, cond*4)
21379           case 8:  // result = lea base(    , cond*8)
21380           case 9:  // result = lea base(cond, cond*8)
21381             isFastMultiplier = true;
21382             break;
21383           }
21384         }
21385
21386         if (isFastMultiplier) {
21387           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21388           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21389                              DAG.getConstant(CC, MVT::i8), Cond);
21390           // Zero extend the condition if needed.
21391           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21392                              Cond);
21393           // Scale the condition by the difference.
21394           if (Diff != 1)
21395             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21396                                DAG.getConstant(Diff, Cond.getValueType()));
21397
21398           // Add the base if non-zero.
21399           if (FalseC->getAPIntValue() != 0)
21400             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21401                                SDValue(FalseC, 0));
21402           if (N->getNumValues() == 2)  // Dead flag value?
21403             return DCI.CombineTo(N, Cond, SDValue());
21404           return Cond;
21405         }
21406       }
21407     }
21408   }
21409
21410   // Handle these cases:
21411   //   (select (x != c), e, c) -> select (x != c), e, x),
21412   //   (select (x == c), c, e) -> select (x == c), x, e)
21413   // where the c is an integer constant, and the "select" is the combination
21414   // of CMOV and CMP.
21415   //
21416   // The rationale for this change is that the conditional-move from a constant
21417   // needs two instructions, however, conditional-move from a register needs
21418   // only one instruction.
21419   //
21420   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21421   //  some instruction-combining opportunities. This opt needs to be
21422   //  postponed as late as possible.
21423   //
21424   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21425     // the DCI.xxxx conditions are provided to postpone the optimization as
21426     // late as possible.
21427
21428     ConstantSDNode *CmpAgainst = nullptr;
21429     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21430         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21431         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21432
21433       if (CC == X86::COND_NE &&
21434           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21435         CC = X86::GetOppositeBranchCondition(CC);
21436         std::swap(TrueOp, FalseOp);
21437       }
21438
21439       if (CC == X86::COND_E &&
21440           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21441         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21442                           DAG.getConstant(CC, MVT::i8), Cond };
21443         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21444       }
21445     }
21446   }
21447
21448   // Fold and/or of setcc's to double CMOV:
21449   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21450   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21451   //
21452   // This combine lets us generate:
21453   //   cmovcc1 (jcc1 if we don't have CMOV)
21454   //   cmovcc2 (same)
21455   // instead of:
21456   //   setcc1
21457   //   setcc2
21458   //   and/or
21459   //   cmovne (jne if we don't have CMOV)
21460   // When we can't use the CMOV instruction, it might increase branch
21461   // mispredicts.
21462   // When we can use CMOV, or when there is no mispredict, this improves
21463   // throughput and reduces register pressure.
21464   //
21465   if (CC == X86::COND_NE) {
21466     SDValue Flags;
21467     X86::CondCode CC0, CC1;
21468     bool isAndSetCC;
21469     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21470       if (isAndSetCC) {
21471         std::swap(FalseOp, TrueOp);
21472         CC0 = X86::GetOppositeBranchCondition(CC0);
21473         CC1 = X86::GetOppositeBranchCondition(CC1);
21474       }
21475
21476       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21477         Flags};
21478       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21479       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21480       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21481       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21482       return CMOV;
21483     }
21484   }
21485
21486   return SDValue();
21487 }
21488
21489 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21490                                                 const X86Subtarget *Subtarget) {
21491   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21492   switch (IntNo) {
21493   default: return SDValue();
21494   // SSE/AVX/AVX2 blend intrinsics.
21495   case Intrinsic::x86_avx2_pblendvb:
21496     // Don't try to simplify this intrinsic if we don't have AVX2.
21497     if (!Subtarget->hasAVX2())
21498       return SDValue();
21499     // FALL-THROUGH
21500   case Intrinsic::x86_avx_blendv_pd_256:
21501   case Intrinsic::x86_avx_blendv_ps_256:
21502     // Don't try to simplify this intrinsic if we don't have AVX.
21503     if (!Subtarget->hasAVX())
21504       return SDValue();
21505     // FALL-THROUGH
21506   case Intrinsic::x86_sse41_blendvps:
21507   case Intrinsic::x86_sse41_blendvpd:
21508   case Intrinsic::x86_sse41_pblendvb: {
21509     SDValue Op0 = N->getOperand(1);
21510     SDValue Op1 = N->getOperand(2);
21511     SDValue Mask = N->getOperand(3);
21512
21513     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21514     if (!Subtarget->hasSSE41())
21515       return SDValue();
21516
21517     // fold (blend A, A, Mask) -> A
21518     if (Op0 == Op1)
21519       return Op0;
21520     // fold (blend A, B, allZeros) -> A
21521     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21522       return Op0;
21523     // fold (blend A, B, allOnes) -> B
21524     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21525       return Op1;
21526
21527     // Simplify the case where the mask is a constant i32 value.
21528     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21529       if (C->isNullValue())
21530         return Op0;
21531       if (C->isAllOnesValue())
21532         return Op1;
21533     }
21534
21535     return SDValue();
21536   }
21537
21538   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21539   case Intrinsic::x86_sse2_psrai_w:
21540   case Intrinsic::x86_sse2_psrai_d:
21541   case Intrinsic::x86_avx2_psrai_w:
21542   case Intrinsic::x86_avx2_psrai_d:
21543   case Intrinsic::x86_sse2_psra_w:
21544   case Intrinsic::x86_sse2_psra_d:
21545   case Intrinsic::x86_avx2_psra_w:
21546   case Intrinsic::x86_avx2_psra_d: {
21547     SDValue Op0 = N->getOperand(1);
21548     SDValue Op1 = N->getOperand(2);
21549     EVT VT = Op0.getValueType();
21550     assert(VT.isVector() && "Expected a vector type!");
21551
21552     if (isa<BuildVectorSDNode>(Op1))
21553       Op1 = Op1.getOperand(0);
21554
21555     if (!isa<ConstantSDNode>(Op1))
21556       return SDValue();
21557
21558     EVT SVT = VT.getVectorElementType();
21559     unsigned SVTBits = SVT.getSizeInBits();
21560
21561     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21562     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21563     uint64_t ShAmt = C.getZExtValue();
21564
21565     // Don't try to convert this shift into a ISD::SRA if the shift
21566     // count is bigger than or equal to the element size.
21567     if (ShAmt >= SVTBits)
21568       return SDValue();
21569
21570     // Trivial case: if the shift count is zero, then fold this
21571     // into the first operand.
21572     if (ShAmt == 0)
21573       return Op0;
21574
21575     // Replace this packed shift intrinsic with a target independent
21576     // shift dag node.
21577     SDValue Splat = DAG.getConstant(C, VT);
21578     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21579   }
21580   }
21581 }
21582
21583 /// PerformMulCombine - Optimize a single multiply with constant into two
21584 /// in order to implement it with two cheaper instructions, e.g.
21585 /// LEA + SHL, LEA + LEA.
21586 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21587                                  TargetLowering::DAGCombinerInfo &DCI) {
21588   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21589     return SDValue();
21590
21591   EVT VT = N->getValueType(0);
21592   if (VT != MVT::i64 && VT != MVT::i32)
21593     return SDValue();
21594
21595   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21596   if (!C)
21597     return SDValue();
21598   uint64_t MulAmt = C->getZExtValue();
21599   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21600     return SDValue();
21601
21602   uint64_t MulAmt1 = 0;
21603   uint64_t MulAmt2 = 0;
21604   if ((MulAmt % 9) == 0) {
21605     MulAmt1 = 9;
21606     MulAmt2 = MulAmt / 9;
21607   } else if ((MulAmt % 5) == 0) {
21608     MulAmt1 = 5;
21609     MulAmt2 = MulAmt / 5;
21610   } else if ((MulAmt % 3) == 0) {
21611     MulAmt1 = 3;
21612     MulAmt2 = MulAmt / 3;
21613   }
21614   if (MulAmt2 &&
21615       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21616     SDLoc DL(N);
21617
21618     if (isPowerOf2_64(MulAmt2) &&
21619         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21620       // If second multiplifer is pow2, issue it first. We want the multiply by
21621       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21622       // is an add.
21623       std::swap(MulAmt1, MulAmt2);
21624
21625     SDValue NewMul;
21626     if (isPowerOf2_64(MulAmt1))
21627       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21628                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21629     else
21630       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21631                            DAG.getConstant(MulAmt1, VT));
21632
21633     if (isPowerOf2_64(MulAmt2))
21634       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21635                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21636     else
21637       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21638                            DAG.getConstant(MulAmt2, VT));
21639
21640     // Do not add new nodes to DAG combiner worklist.
21641     DCI.CombineTo(N, NewMul, false);
21642   }
21643   return SDValue();
21644 }
21645
21646 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21647   SDValue N0 = N->getOperand(0);
21648   SDValue N1 = N->getOperand(1);
21649   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21650   EVT VT = N0.getValueType();
21651
21652   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21653   // since the result of setcc_c is all zero's or all ones.
21654   if (VT.isInteger() && !VT.isVector() &&
21655       N1C && N0.getOpcode() == ISD::AND &&
21656       N0.getOperand(1).getOpcode() == ISD::Constant) {
21657     SDValue N00 = N0.getOperand(0);
21658     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21659         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21660           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21661          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21662       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21663       APInt ShAmt = N1C->getAPIntValue();
21664       Mask = Mask.shl(ShAmt);
21665       if (Mask != 0)
21666         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21667                            N00, DAG.getConstant(Mask, VT));
21668     }
21669   }
21670
21671   // Hardware support for vector shifts is sparse which makes us scalarize the
21672   // vector operations in many cases. Also, on sandybridge ADD is faster than
21673   // shl.
21674   // (shl V, 1) -> add V,V
21675   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21676     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21677       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21678       // We shift all of the values by one. In many cases we do not have
21679       // hardware support for this operation. This is better expressed as an ADD
21680       // of two values.
21681       if (N1SplatC->getZExtValue() == 1)
21682         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21683     }
21684
21685   return SDValue();
21686 }
21687
21688 /// \brief Returns a vector of 0s if the node in input is a vector logical
21689 /// shift by a constant amount which is known to be bigger than or equal
21690 /// to the vector element size in bits.
21691 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21692                                       const X86Subtarget *Subtarget) {
21693   EVT VT = N->getValueType(0);
21694
21695   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21696       (!Subtarget->hasInt256() ||
21697        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21698     return SDValue();
21699
21700   SDValue Amt = N->getOperand(1);
21701   SDLoc DL(N);
21702   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21703     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21704       APInt ShiftAmt = AmtSplat->getAPIntValue();
21705       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21706
21707       // SSE2/AVX2 logical shifts always return a vector of 0s
21708       // if the shift amount is bigger than or equal to
21709       // the element size. The constant shift amount will be
21710       // encoded as a 8-bit immediate.
21711       if (ShiftAmt.trunc(8).uge(MaxAmount))
21712         return getZeroVector(VT, Subtarget, DAG, DL);
21713     }
21714
21715   return SDValue();
21716 }
21717
21718 /// PerformShiftCombine - Combine shifts.
21719 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21720                                    TargetLowering::DAGCombinerInfo &DCI,
21721                                    const X86Subtarget *Subtarget) {
21722   if (N->getOpcode() == ISD::SHL) {
21723     SDValue V = PerformSHLCombine(N, DAG);
21724     if (V.getNode()) return V;
21725   }
21726
21727   if (N->getOpcode() != ISD::SRA) {
21728     // Try to fold this logical shift into a zero vector.
21729     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21730     if (V.getNode()) return V;
21731   }
21732
21733   return SDValue();
21734 }
21735
21736 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21737 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21738 // and friends.  Likewise for OR -> CMPNEQSS.
21739 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21740                             TargetLowering::DAGCombinerInfo &DCI,
21741                             const X86Subtarget *Subtarget) {
21742   unsigned opcode;
21743
21744   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21745   // we're requiring SSE2 for both.
21746   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21747     SDValue N0 = N->getOperand(0);
21748     SDValue N1 = N->getOperand(1);
21749     SDValue CMP0 = N0->getOperand(1);
21750     SDValue CMP1 = N1->getOperand(1);
21751     SDLoc DL(N);
21752
21753     // The SETCCs should both refer to the same CMP.
21754     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21755       return SDValue();
21756
21757     SDValue CMP00 = CMP0->getOperand(0);
21758     SDValue CMP01 = CMP0->getOperand(1);
21759     EVT     VT    = CMP00.getValueType();
21760
21761     if (VT == MVT::f32 || VT == MVT::f64) {
21762       bool ExpectingFlags = false;
21763       // Check for any users that want flags:
21764       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21765            !ExpectingFlags && UI != UE; ++UI)
21766         switch (UI->getOpcode()) {
21767         default:
21768         case ISD::BR_CC:
21769         case ISD::BRCOND:
21770         case ISD::SELECT:
21771           ExpectingFlags = true;
21772           break;
21773         case ISD::CopyToReg:
21774         case ISD::SIGN_EXTEND:
21775         case ISD::ZERO_EXTEND:
21776         case ISD::ANY_EXTEND:
21777           break;
21778         }
21779
21780       if (!ExpectingFlags) {
21781         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21782         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21783
21784         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21785           X86::CondCode tmp = cc0;
21786           cc0 = cc1;
21787           cc1 = tmp;
21788         }
21789
21790         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21791             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21792           // FIXME: need symbolic constants for these magic numbers.
21793           // See X86ATTInstPrinter.cpp:printSSECC().
21794           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21795           if (Subtarget->hasAVX512()) {
21796             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21797                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21798             if (N->getValueType(0) != MVT::i1)
21799               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21800                                  FSetCC);
21801             return FSetCC;
21802           }
21803           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21804                                               CMP00.getValueType(), CMP00, CMP01,
21805                                               DAG.getConstant(x86cc, MVT::i8));
21806
21807           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21808           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21809
21810           if (is64BitFP && !Subtarget->is64Bit()) {
21811             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21812             // 64-bit integer, since that's not a legal type. Since
21813             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21814             // bits, but can do this little dance to extract the lowest 32 bits
21815             // and work with those going forward.
21816             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21817                                            OnesOrZeroesF);
21818             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21819                                            Vector64);
21820             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21821                                         Vector32, DAG.getIntPtrConstant(0));
21822             IntVT = MVT::i32;
21823           }
21824
21825           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21826           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21827                                       DAG.getConstant(1, IntVT));
21828           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21829           return OneBitOfTruth;
21830         }
21831       }
21832     }
21833   }
21834   return SDValue();
21835 }
21836
21837 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21838 /// so it can be folded inside ANDNP.
21839 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21840   EVT VT = N->getValueType(0);
21841
21842   // Match direct AllOnes for 128 and 256-bit vectors
21843   if (ISD::isBuildVectorAllOnes(N))
21844     return true;
21845
21846   // Look through a bit convert.
21847   if (N->getOpcode() == ISD::BITCAST)
21848     N = N->getOperand(0).getNode();
21849
21850   // Sometimes the operand may come from a insert_subvector building a 256-bit
21851   // allones vector
21852   if (VT.is256BitVector() &&
21853       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21854     SDValue V1 = N->getOperand(0);
21855     SDValue V2 = N->getOperand(1);
21856
21857     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21858         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21859         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21860         ISD::isBuildVectorAllOnes(V2.getNode()))
21861       return true;
21862   }
21863
21864   return false;
21865 }
21866
21867 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21868 // register. In most cases we actually compare or select YMM-sized registers
21869 // and mixing the two types creates horrible code. This method optimizes
21870 // some of the transition sequences.
21871 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21872                                  TargetLowering::DAGCombinerInfo &DCI,
21873                                  const X86Subtarget *Subtarget) {
21874   EVT VT = N->getValueType(0);
21875   if (!VT.is256BitVector())
21876     return SDValue();
21877
21878   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21879           N->getOpcode() == ISD::ZERO_EXTEND ||
21880           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21881
21882   SDValue Narrow = N->getOperand(0);
21883   EVT NarrowVT = Narrow->getValueType(0);
21884   if (!NarrowVT.is128BitVector())
21885     return SDValue();
21886
21887   if (Narrow->getOpcode() != ISD::XOR &&
21888       Narrow->getOpcode() != ISD::AND &&
21889       Narrow->getOpcode() != ISD::OR)
21890     return SDValue();
21891
21892   SDValue N0  = Narrow->getOperand(0);
21893   SDValue N1  = Narrow->getOperand(1);
21894   SDLoc DL(Narrow);
21895
21896   // The Left side has to be a trunc.
21897   if (N0.getOpcode() != ISD::TRUNCATE)
21898     return SDValue();
21899
21900   // The type of the truncated inputs.
21901   EVT WideVT = N0->getOperand(0)->getValueType(0);
21902   if (WideVT != VT)
21903     return SDValue();
21904
21905   // The right side has to be a 'trunc' or a constant vector.
21906   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21907   ConstantSDNode *RHSConstSplat = nullptr;
21908   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21909     RHSConstSplat = RHSBV->getConstantSplatNode();
21910   if (!RHSTrunc && !RHSConstSplat)
21911     return SDValue();
21912
21913   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21914
21915   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21916     return SDValue();
21917
21918   // Set N0 and N1 to hold the inputs to the new wide operation.
21919   N0 = N0->getOperand(0);
21920   if (RHSConstSplat) {
21921     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21922                      SDValue(RHSConstSplat, 0));
21923     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21924     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21925   } else if (RHSTrunc) {
21926     N1 = N1->getOperand(0);
21927   }
21928
21929   // Generate the wide operation.
21930   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21931   unsigned Opcode = N->getOpcode();
21932   switch (Opcode) {
21933   case ISD::ANY_EXTEND:
21934     return Op;
21935   case ISD::ZERO_EXTEND: {
21936     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21937     APInt Mask = APInt::getAllOnesValue(InBits);
21938     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21939     return DAG.getNode(ISD::AND, DL, VT,
21940                        Op, DAG.getConstant(Mask, VT));
21941   }
21942   case ISD::SIGN_EXTEND:
21943     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21944                        Op, DAG.getValueType(NarrowVT));
21945   default:
21946     llvm_unreachable("Unexpected opcode");
21947   }
21948 }
21949
21950 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
21951                                  TargetLowering::DAGCombinerInfo &DCI,
21952                                  const X86Subtarget *Subtarget) {
21953   SDValue N0 = N->getOperand(0);
21954   SDValue N1 = N->getOperand(1);
21955   SDLoc DL(N);
21956
21957   // A vector zext_in_reg may be represented as a shuffle,
21958   // feeding into a bitcast (this represents anyext) feeding into
21959   // an and with a mask.
21960   // We'd like to try to combine that into a shuffle with zero
21961   // plus a bitcast, removing the and.
21962   if (N0.getOpcode() != ISD::BITCAST || 
21963       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
21964     return SDValue();
21965
21966   // The other side of the AND should be a splat of 2^C, where C
21967   // is the number of bits in the source type.
21968   if (N1.getOpcode() == ISD::BITCAST)
21969     N1 = N1.getOperand(0);
21970   if (N1.getOpcode() != ISD::BUILD_VECTOR)
21971     return SDValue();
21972   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
21973
21974   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
21975   EVT SrcType = Shuffle->getValueType(0);
21976
21977   // We expect a single-source shuffle
21978   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
21979     return SDValue();
21980
21981   unsigned SrcSize = SrcType.getScalarSizeInBits();
21982
21983   APInt SplatValue, SplatUndef;
21984   unsigned SplatBitSize;
21985   bool HasAnyUndefs;
21986   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
21987                                 SplatBitSize, HasAnyUndefs))
21988     return SDValue();
21989
21990   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
21991   // Make sure the splat matches the mask we expect
21992   if (SplatBitSize > ResSize || 
21993       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
21994     return SDValue();
21995
21996   // Make sure the input and output size make sense
21997   if (SrcSize >= ResSize || ResSize % SrcSize)
21998     return SDValue();
21999
22000   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22001   // The number of u's between each two values depends on the ratio between
22002   // the source and dest type.
22003   unsigned ZextRatio = ResSize / SrcSize;
22004   bool IsZext = true;
22005   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22006     if (i % ZextRatio) {
22007       if (Shuffle->getMaskElt(i) > 0) {
22008         // Expected undef
22009         IsZext = false;
22010         break;
22011       }
22012     } else {
22013       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22014         // Expected element number
22015         IsZext = false;
22016         break;
22017       }
22018     }
22019   }
22020
22021   if (!IsZext)
22022     return SDValue();
22023
22024   // Ok, perform the transformation - replace the shuffle with
22025   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22026   // (instead of undef) where the k elements come from the zero vector.
22027   SmallVector<int, 8> Mask;
22028   unsigned NumElems = SrcType.getVectorNumElements();
22029   for (unsigned i = 0; i < NumElems; ++i)
22030     if (i % ZextRatio)
22031       Mask.push_back(NumElems);
22032     else
22033       Mask.push_back(i / ZextRatio);
22034
22035   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22036     Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
22037   return DAG.getNode(ISD::BITCAST, DL,  N0.getValueType(), NewShuffle);
22038 }
22039
22040 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22041                                  TargetLowering::DAGCombinerInfo &DCI,
22042                                  const X86Subtarget *Subtarget) {
22043   if (DCI.isBeforeLegalizeOps())
22044     return SDValue();
22045
22046   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22047     return Zext;
22048
22049   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22050     return R;
22051
22052   EVT VT = N->getValueType(0);
22053   SDValue N0 = N->getOperand(0);
22054   SDValue N1 = N->getOperand(1);
22055   SDLoc DL(N);
22056
22057   // Create BEXTR instructions
22058   // BEXTR is ((X >> imm) & (2**size-1))
22059   if (VT == MVT::i32 || VT == MVT::i64) {
22060     // Check for BEXTR.
22061     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22062         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22063       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22064       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22065       if (MaskNode && ShiftNode) {
22066         uint64_t Mask = MaskNode->getZExtValue();
22067         uint64_t Shift = ShiftNode->getZExtValue();
22068         if (isMask_64(Mask)) {
22069           uint64_t MaskSize = countPopulation(Mask);
22070           if (Shift + MaskSize <= VT.getSizeInBits())
22071             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22072                                DAG.getConstant(Shift | (MaskSize << 8), VT));
22073         }
22074       }
22075     } // BEXTR
22076
22077     return SDValue();
22078   }
22079
22080   // Want to form ANDNP nodes:
22081   // 1) In the hopes of then easily combining them with OR and AND nodes
22082   //    to form PBLEND/PSIGN.
22083   // 2) To match ANDN packed intrinsics
22084   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22085     return SDValue();
22086
22087   // Check LHS for vnot
22088   if (N0.getOpcode() == ISD::XOR &&
22089       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22090       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22091     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22092
22093   // Check RHS for vnot
22094   if (N1.getOpcode() == ISD::XOR &&
22095       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22096       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22097     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22098
22099   return SDValue();
22100 }
22101
22102 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22103                                 TargetLowering::DAGCombinerInfo &DCI,
22104                                 const X86Subtarget *Subtarget) {
22105   if (DCI.isBeforeLegalizeOps())
22106     return SDValue();
22107
22108   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22109   if (R.getNode())
22110     return R;
22111
22112   SDValue N0 = N->getOperand(0);
22113   SDValue N1 = N->getOperand(1);
22114   EVT VT = N->getValueType(0);
22115
22116   // look for psign/blend
22117   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22118     if (!Subtarget->hasSSSE3() ||
22119         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22120       return SDValue();
22121
22122     // Canonicalize pandn to RHS
22123     if (N0.getOpcode() == X86ISD::ANDNP)
22124       std::swap(N0, N1);
22125     // or (and (m, y), (pandn m, x))
22126     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22127       SDValue Mask = N1.getOperand(0);
22128       SDValue X    = N1.getOperand(1);
22129       SDValue Y;
22130       if (N0.getOperand(0) == Mask)
22131         Y = N0.getOperand(1);
22132       if (N0.getOperand(1) == Mask)
22133         Y = N0.getOperand(0);
22134
22135       // Check to see if the mask appeared in both the AND and ANDNP and
22136       if (!Y.getNode())
22137         return SDValue();
22138
22139       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22140       // Look through mask bitcast.
22141       if (Mask.getOpcode() == ISD::BITCAST)
22142         Mask = Mask.getOperand(0);
22143       if (X.getOpcode() == ISD::BITCAST)
22144         X = X.getOperand(0);
22145       if (Y.getOpcode() == ISD::BITCAST)
22146         Y = Y.getOperand(0);
22147
22148       EVT MaskVT = Mask.getValueType();
22149
22150       // Validate that the Mask operand is a vector sra node.
22151       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22152       // there is no psrai.b
22153       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22154       unsigned SraAmt = ~0;
22155       if (Mask.getOpcode() == ISD::SRA) {
22156         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22157           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22158             SraAmt = AmtConst->getZExtValue();
22159       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22160         SDValue SraC = Mask.getOperand(1);
22161         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22162       }
22163       if ((SraAmt + 1) != EltBits)
22164         return SDValue();
22165
22166       SDLoc DL(N);
22167
22168       // Now we know we at least have a plendvb with the mask val.  See if
22169       // we can form a psignb/w/d.
22170       // psign = x.type == y.type == mask.type && y = sub(0, x);
22171       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22172           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22173           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22174         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22175                "Unsupported VT for PSIGN");
22176         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22177         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22178       }
22179       // PBLENDVB only available on SSE 4.1
22180       if (!Subtarget->hasSSE41())
22181         return SDValue();
22182
22183       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22184
22185       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22186       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22187       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22188       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22189       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22190     }
22191   }
22192
22193   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22194     return SDValue();
22195
22196   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22197   MachineFunction &MF = DAG.getMachineFunction();
22198   bool OptForSize =
22199       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22200
22201   // SHLD/SHRD instructions have lower register pressure, but on some
22202   // platforms they have higher latency than the equivalent
22203   // series of shifts/or that would otherwise be generated.
22204   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22205   // have higher latencies and we are not optimizing for size.
22206   if (!OptForSize && Subtarget->isSHLDSlow())
22207     return SDValue();
22208
22209   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22210     std::swap(N0, N1);
22211   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22212     return SDValue();
22213   if (!N0.hasOneUse() || !N1.hasOneUse())
22214     return SDValue();
22215
22216   SDValue ShAmt0 = N0.getOperand(1);
22217   if (ShAmt0.getValueType() != MVT::i8)
22218     return SDValue();
22219   SDValue ShAmt1 = N1.getOperand(1);
22220   if (ShAmt1.getValueType() != MVT::i8)
22221     return SDValue();
22222   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22223     ShAmt0 = ShAmt0.getOperand(0);
22224   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22225     ShAmt1 = ShAmt1.getOperand(0);
22226
22227   SDLoc DL(N);
22228   unsigned Opc = X86ISD::SHLD;
22229   SDValue Op0 = N0.getOperand(0);
22230   SDValue Op1 = N1.getOperand(0);
22231   if (ShAmt0.getOpcode() == ISD::SUB) {
22232     Opc = X86ISD::SHRD;
22233     std::swap(Op0, Op1);
22234     std::swap(ShAmt0, ShAmt1);
22235   }
22236
22237   unsigned Bits = VT.getSizeInBits();
22238   if (ShAmt1.getOpcode() == ISD::SUB) {
22239     SDValue Sum = ShAmt1.getOperand(0);
22240     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22241       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22242       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22243         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22244       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22245         return DAG.getNode(Opc, DL, VT,
22246                            Op0, Op1,
22247                            DAG.getNode(ISD::TRUNCATE, DL,
22248                                        MVT::i8, ShAmt0));
22249     }
22250   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22251     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22252     if (ShAmt0C &&
22253         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22254       return DAG.getNode(Opc, DL, VT,
22255                          N0.getOperand(0), N1.getOperand(0),
22256                          DAG.getNode(ISD::TRUNCATE, DL,
22257                                        MVT::i8, ShAmt0));
22258   }
22259
22260   return SDValue();
22261 }
22262
22263 // Generate NEG and CMOV for integer abs.
22264 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22265   EVT VT = N->getValueType(0);
22266
22267   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22268   // 8-bit integer abs to NEG and CMOV.
22269   if (VT.isInteger() && VT.getSizeInBits() == 8)
22270     return SDValue();
22271
22272   SDValue N0 = N->getOperand(0);
22273   SDValue N1 = N->getOperand(1);
22274   SDLoc DL(N);
22275
22276   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22277   // and change it to SUB and CMOV.
22278   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22279       N0.getOpcode() == ISD::ADD &&
22280       N0.getOperand(1) == N1 &&
22281       N1.getOpcode() == ISD::SRA &&
22282       N1.getOperand(0) == N0.getOperand(0))
22283     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22284       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22285         // Generate SUB & CMOV.
22286         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22287                                   DAG.getConstant(0, VT), N0.getOperand(0));
22288
22289         SDValue Ops[] = { N0.getOperand(0), Neg,
22290                           DAG.getConstant(X86::COND_GE, MVT::i8),
22291                           SDValue(Neg.getNode(), 1) };
22292         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22293       }
22294   return SDValue();
22295 }
22296
22297 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22298 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22299                                  TargetLowering::DAGCombinerInfo &DCI,
22300                                  const X86Subtarget *Subtarget) {
22301   if (DCI.isBeforeLegalizeOps())
22302     return SDValue();
22303
22304   if (Subtarget->hasCMov()) {
22305     SDValue RV = performIntegerAbsCombine(N, DAG);
22306     if (RV.getNode())
22307       return RV;
22308   }
22309
22310   return SDValue();
22311 }
22312
22313 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22314 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22315                                   TargetLowering::DAGCombinerInfo &DCI,
22316                                   const X86Subtarget *Subtarget) {
22317   LoadSDNode *Ld = cast<LoadSDNode>(N);
22318   EVT RegVT = Ld->getValueType(0);
22319   EVT MemVT = Ld->getMemoryVT();
22320   SDLoc dl(Ld);
22321   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22322
22323   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22324   // into two 16-byte operations.
22325   ISD::LoadExtType Ext = Ld->getExtensionType();
22326   unsigned Alignment = Ld->getAlignment();
22327   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22328   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22329       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22330     unsigned NumElems = RegVT.getVectorNumElements();
22331     if (NumElems < 2)
22332       return SDValue();
22333
22334     SDValue Ptr = Ld->getBasePtr();
22335     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22336
22337     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22338                                   NumElems/2);
22339     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22340                                 Ld->getPointerInfo(), Ld->isVolatile(),
22341                                 Ld->isNonTemporal(), Ld->isInvariant(),
22342                                 Alignment);
22343     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22344     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22345                                 Ld->getPointerInfo(), Ld->isVolatile(),
22346                                 Ld->isNonTemporal(), Ld->isInvariant(),
22347                                 std::min(16U, Alignment));
22348     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22349                              Load1.getValue(1),
22350                              Load2.getValue(1));
22351
22352     SDValue NewVec = DAG.getUNDEF(RegVT);
22353     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22354     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22355     return DCI.CombineTo(N, NewVec, TF, true);
22356   }
22357
22358   return SDValue();
22359 }
22360
22361 /// PerformMLOADCombine - Resolve extending loads
22362 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22363                                    TargetLowering::DAGCombinerInfo &DCI,
22364                                    const X86Subtarget *Subtarget) {
22365   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22366   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22367     return SDValue();
22368
22369   EVT VT = Mld->getValueType(0);
22370   unsigned NumElems = VT.getVectorNumElements();
22371   EVT LdVT = Mld->getMemoryVT();
22372   SDLoc dl(Mld);
22373
22374   assert(LdVT != VT && "Cannot extend to the same type");
22375   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22376   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22377   // From, To sizes and ElemCount must be pow of two
22378   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22379     "Unexpected size for extending masked load");
22380
22381   unsigned SizeRatio  = ToSz / FromSz;
22382   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22383
22384   // Create a type on which we perform the shuffle
22385   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22386           LdVT.getScalarType(), NumElems*SizeRatio);
22387   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22388
22389   // Convert Src0 value
22390   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22391   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22392     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22393     for (unsigned i = 0; i != NumElems; ++i)
22394       ShuffleVec[i] = i * SizeRatio;
22395
22396     // Can't shuffle using an illegal type.
22397     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22398             && "WideVecVT should be legal");
22399     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22400                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22401   }
22402   // Prepare the new mask
22403   SDValue NewMask;
22404   SDValue Mask = Mld->getMask();
22405   if (Mask.getValueType() == VT) {
22406     // Mask and original value have the same type
22407     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22408     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22409     for (unsigned i = 0; i != NumElems; ++i)
22410       ShuffleVec[i] = i * SizeRatio;
22411     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22412       ShuffleVec[i] = NumElems*SizeRatio;
22413     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22414                                    DAG.getConstant(0, WideVecVT),
22415                                    &ShuffleVec[0]);
22416   }
22417   else {
22418     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22419     unsigned WidenNumElts = NumElems*SizeRatio;
22420     unsigned MaskNumElts = VT.getVectorNumElements();
22421     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22422                                      WidenNumElts);
22423
22424     unsigned NumConcat = WidenNumElts / MaskNumElts;
22425     SmallVector<SDValue, 16> Ops(NumConcat);
22426     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22427     Ops[0] = Mask;
22428     for (unsigned i = 1; i != NumConcat; ++i)
22429       Ops[i] = ZeroVal;
22430
22431     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22432   }
22433
22434   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22435                                      Mld->getBasePtr(), NewMask, WideSrc0,
22436                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22437                                      ISD::NON_EXTLOAD);
22438   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22439   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22440
22441 }
22442 /// PerformMSTORECombine - Resolve truncating stores
22443 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22444                                     const X86Subtarget *Subtarget) {
22445   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22446   if (!Mst->isTruncatingStore())
22447     return SDValue();
22448
22449   EVT VT = Mst->getValue().getValueType();
22450   unsigned NumElems = VT.getVectorNumElements();
22451   EVT StVT = Mst->getMemoryVT();
22452   SDLoc dl(Mst);
22453
22454   assert(StVT != VT && "Cannot truncate to the same type");
22455   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22456   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22457
22458   // From, To sizes and ElemCount must be pow of two
22459   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22460     "Unexpected size for truncating masked store");
22461   // We are going to use the original vector elt for storing.
22462   // Accumulated smaller vector elements must be a multiple of the store size.
22463   assert (((NumElems * FromSz) % ToSz) == 0 &&
22464           "Unexpected ratio for truncating masked store");
22465
22466   unsigned SizeRatio  = FromSz / ToSz;
22467   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22468
22469   // Create a type on which we perform the shuffle
22470   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22471           StVT.getScalarType(), NumElems*SizeRatio);
22472
22473   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22474
22475   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22476   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22477   for (unsigned i = 0; i != NumElems; ++i)
22478     ShuffleVec[i] = i * SizeRatio;
22479
22480   // Can't shuffle using an illegal type.
22481   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22482           && "WideVecVT should be legal");
22483
22484   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22485                                         DAG.getUNDEF(WideVecVT),
22486                                         &ShuffleVec[0]);
22487
22488   SDValue NewMask;
22489   SDValue Mask = Mst->getMask();
22490   if (Mask.getValueType() == VT) {
22491     // Mask and original value have the same type
22492     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22493     for (unsigned i = 0; i != NumElems; ++i)
22494       ShuffleVec[i] = i * SizeRatio;
22495     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22496       ShuffleVec[i] = NumElems*SizeRatio;
22497     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22498                                    DAG.getConstant(0, WideVecVT),
22499                                    &ShuffleVec[0]);
22500   }
22501   else {
22502     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22503     unsigned WidenNumElts = NumElems*SizeRatio;
22504     unsigned MaskNumElts = VT.getVectorNumElements();
22505     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22506                                      WidenNumElts);
22507
22508     unsigned NumConcat = WidenNumElts / MaskNumElts;
22509     SmallVector<SDValue, 16> Ops(NumConcat);
22510     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22511     Ops[0] = Mask;
22512     for (unsigned i = 1; i != NumConcat; ++i)
22513       Ops[i] = ZeroVal;
22514
22515     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22516   }
22517
22518   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22519                             NewMask, StVT, Mst->getMemOperand(), false);
22520 }
22521 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22522 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22523                                    const X86Subtarget *Subtarget) {
22524   StoreSDNode *St = cast<StoreSDNode>(N);
22525   EVT VT = St->getValue().getValueType();
22526   EVT StVT = St->getMemoryVT();
22527   SDLoc dl(St);
22528   SDValue StoredVal = St->getOperand(1);
22529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22530
22531   // If we are saving a concatenation of two XMM registers and 32-byte stores
22532   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22533   unsigned Alignment = St->getAlignment();
22534   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22535   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22536       StVT == VT && !IsAligned) {
22537     unsigned NumElems = VT.getVectorNumElements();
22538     if (NumElems < 2)
22539       return SDValue();
22540
22541     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22542     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22543
22544     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22545     SDValue Ptr0 = St->getBasePtr();
22546     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22547
22548     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22549                                 St->getPointerInfo(), St->isVolatile(),
22550                                 St->isNonTemporal(), Alignment);
22551     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22552                                 St->getPointerInfo(), St->isVolatile(),
22553                                 St->isNonTemporal(),
22554                                 std::min(16U, Alignment));
22555     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22556   }
22557
22558   // Optimize trunc store (of multiple scalars) to shuffle and store.
22559   // First, pack all of the elements in one place. Next, store to memory
22560   // in fewer chunks.
22561   if (St->isTruncatingStore() && VT.isVector()) {
22562     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22563     unsigned NumElems = VT.getVectorNumElements();
22564     assert(StVT != VT && "Cannot truncate to the same type");
22565     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22566     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22567
22568     // From, To sizes and ElemCount must be pow of two
22569     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22570     // We are going to use the original vector elt for storing.
22571     // Accumulated smaller vector elements must be a multiple of the store size.
22572     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22573
22574     unsigned SizeRatio  = FromSz / ToSz;
22575
22576     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22577
22578     // Create a type on which we perform the shuffle
22579     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22580             StVT.getScalarType(), NumElems*SizeRatio);
22581
22582     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22583
22584     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22585     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22586     for (unsigned i = 0; i != NumElems; ++i)
22587       ShuffleVec[i] = i * SizeRatio;
22588
22589     // Can't shuffle using an illegal type.
22590     if (!TLI.isTypeLegal(WideVecVT))
22591       return SDValue();
22592
22593     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22594                                          DAG.getUNDEF(WideVecVT),
22595                                          &ShuffleVec[0]);
22596     // At this point all of the data is stored at the bottom of the
22597     // register. We now need to save it to mem.
22598
22599     // Find the largest store unit
22600     MVT StoreType = MVT::i8;
22601     for (MVT Tp : MVT::integer_valuetypes()) {
22602       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22603         StoreType = Tp;
22604     }
22605
22606     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22607     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22608         (64 <= NumElems * ToSz))
22609       StoreType = MVT::f64;
22610
22611     // Bitcast the original vector into a vector of store-size units
22612     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22613             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22614     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22615     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22616     SmallVector<SDValue, 8> Chains;
22617     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22618                                         TLI.getPointerTy());
22619     SDValue Ptr = St->getBasePtr();
22620
22621     // Perform one or more big stores into memory.
22622     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22623       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22624                                    StoreType, ShuffWide,
22625                                    DAG.getIntPtrConstant(i));
22626       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22627                                 St->getPointerInfo(), St->isVolatile(),
22628                                 St->isNonTemporal(), St->getAlignment());
22629       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22630       Chains.push_back(Ch);
22631     }
22632
22633     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22634   }
22635
22636   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22637   // the FP state in cases where an emms may be missing.
22638   // A preferable solution to the general problem is to figure out the right
22639   // places to insert EMMS.  This qualifies as a quick hack.
22640
22641   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22642   if (VT.getSizeInBits() != 64)
22643     return SDValue();
22644
22645   const Function *F = DAG.getMachineFunction().getFunction();
22646   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22647   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22648                      && Subtarget->hasSSE2();
22649   if ((VT.isVector() ||
22650        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22651       isa<LoadSDNode>(St->getValue()) &&
22652       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22653       St->getChain().hasOneUse() && !St->isVolatile()) {
22654     SDNode* LdVal = St->getValue().getNode();
22655     LoadSDNode *Ld = nullptr;
22656     int TokenFactorIndex = -1;
22657     SmallVector<SDValue, 8> Ops;
22658     SDNode* ChainVal = St->getChain().getNode();
22659     // Must be a store of a load.  We currently handle two cases:  the load
22660     // is a direct child, and it's under an intervening TokenFactor.  It is
22661     // possible to dig deeper under nested TokenFactors.
22662     if (ChainVal == LdVal)
22663       Ld = cast<LoadSDNode>(St->getChain());
22664     else if (St->getValue().hasOneUse() &&
22665              ChainVal->getOpcode() == ISD::TokenFactor) {
22666       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22667         if (ChainVal->getOperand(i).getNode() == LdVal) {
22668           TokenFactorIndex = i;
22669           Ld = cast<LoadSDNode>(St->getValue());
22670         } else
22671           Ops.push_back(ChainVal->getOperand(i));
22672       }
22673     }
22674
22675     if (!Ld || !ISD::isNormalLoad(Ld))
22676       return SDValue();
22677
22678     // If this is not the MMX case, i.e. we are just turning i64 load/store
22679     // into f64 load/store, avoid the transformation if there are multiple
22680     // uses of the loaded value.
22681     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22682       return SDValue();
22683
22684     SDLoc LdDL(Ld);
22685     SDLoc StDL(N);
22686     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22687     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22688     // pair instead.
22689     if (Subtarget->is64Bit() || F64IsLegal) {
22690       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22691       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22692                                   Ld->getPointerInfo(), Ld->isVolatile(),
22693                                   Ld->isNonTemporal(), Ld->isInvariant(),
22694                                   Ld->getAlignment());
22695       SDValue NewChain = NewLd.getValue(1);
22696       if (TokenFactorIndex != -1) {
22697         Ops.push_back(NewChain);
22698         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22699       }
22700       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22701                           St->getPointerInfo(),
22702                           St->isVolatile(), St->isNonTemporal(),
22703                           St->getAlignment());
22704     }
22705
22706     // Otherwise, lower to two pairs of 32-bit loads / stores.
22707     SDValue LoAddr = Ld->getBasePtr();
22708     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22709                                  DAG.getConstant(4, MVT::i32));
22710
22711     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22712                                Ld->getPointerInfo(),
22713                                Ld->isVolatile(), Ld->isNonTemporal(),
22714                                Ld->isInvariant(), Ld->getAlignment());
22715     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22716                                Ld->getPointerInfo().getWithOffset(4),
22717                                Ld->isVolatile(), Ld->isNonTemporal(),
22718                                Ld->isInvariant(),
22719                                MinAlign(Ld->getAlignment(), 4));
22720
22721     SDValue NewChain = LoLd.getValue(1);
22722     if (TokenFactorIndex != -1) {
22723       Ops.push_back(LoLd);
22724       Ops.push_back(HiLd);
22725       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22726     }
22727
22728     LoAddr = St->getBasePtr();
22729     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22730                          DAG.getConstant(4, MVT::i32));
22731
22732     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22733                                 St->getPointerInfo(),
22734                                 St->isVolatile(), St->isNonTemporal(),
22735                                 St->getAlignment());
22736     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22737                                 St->getPointerInfo().getWithOffset(4),
22738                                 St->isVolatile(),
22739                                 St->isNonTemporal(),
22740                                 MinAlign(St->getAlignment(), 4));
22741     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22742   }
22743   return SDValue();
22744 }
22745
22746 /// Return 'true' if this vector operation is "horizontal"
22747 /// and return the operands for the horizontal operation in LHS and RHS.  A
22748 /// horizontal operation performs the binary operation on successive elements
22749 /// of its first operand, then on successive elements of its second operand,
22750 /// returning the resulting values in a vector.  For example, if
22751 ///   A = < float a0, float a1, float a2, float a3 >
22752 /// and
22753 ///   B = < float b0, float b1, float b2, float b3 >
22754 /// then the result of doing a horizontal operation on A and B is
22755 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22756 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22757 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22758 /// set to A, RHS to B, and the routine returns 'true'.
22759 /// Note that the binary operation should have the property that if one of the
22760 /// operands is UNDEF then the result is UNDEF.
22761 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22762   // Look for the following pattern: if
22763   //   A = < float a0, float a1, float a2, float a3 >
22764   //   B = < float b0, float b1, float b2, float b3 >
22765   // and
22766   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22767   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22768   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22769   // which is A horizontal-op B.
22770
22771   // At least one of the operands should be a vector shuffle.
22772   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22773       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22774     return false;
22775
22776   MVT VT = LHS.getSimpleValueType();
22777
22778   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22779          "Unsupported vector type for horizontal add/sub");
22780
22781   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22782   // operate independently on 128-bit lanes.
22783   unsigned NumElts = VT.getVectorNumElements();
22784   unsigned NumLanes = VT.getSizeInBits()/128;
22785   unsigned NumLaneElts = NumElts / NumLanes;
22786   assert((NumLaneElts % 2 == 0) &&
22787          "Vector type should have an even number of elements in each lane");
22788   unsigned HalfLaneElts = NumLaneElts/2;
22789
22790   // View LHS in the form
22791   //   LHS = VECTOR_SHUFFLE A, B, LMask
22792   // If LHS is not a shuffle then pretend it is the shuffle
22793   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22794   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22795   // type VT.
22796   SDValue A, B;
22797   SmallVector<int, 16> LMask(NumElts);
22798   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22799     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22800       A = LHS.getOperand(0);
22801     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22802       B = LHS.getOperand(1);
22803     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22804     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22805   } else {
22806     if (LHS.getOpcode() != ISD::UNDEF)
22807       A = LHS;
22808     for (unsigned i = 0; i != NumElts; ++i)
22809       LMask[i] = i;
22810   }
22811
22812   // Likewise, view RHS in the form
22813   //   RHS = VECTOR_SHUFFLE C, D, RMask
22814   SDValue C, D;
22815   SmallVector<int, 16> RMask(NumElts);
22816   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22817     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22818       C = RHS.getOperand(0);
22819     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22820       D = RHS.getOperand(1);
22821     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22822     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22823   } else {
22824     if (RHS.getOpcode() != ISD::UNDEF)
22825       C = RHS;
22826     for (unsigned i = 0; i != NumElts; ++i)
22827       RMask[i] = i;
22828   }
22829
22830   // Check that the shuffles are both shuffling the same vectors.
22831   if (!(A == C && B == D) && !(A == D && B == C))
22832     return false;
22833
22834   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22835   if (!A.getNode() && !B.getNode())
22836     return false;
22837
22838   // If A and B occur in reverse order in RHS, then "swap" them (which means
22839   // rewriting the mask).
22840   if (A != C)
22841     ShuffleVectorSDNode::commuteMask(RMask);
22842
22843   // At this point LHS and RHS are equivalent to
22844   //   LHS = VECTOR_SHUFFLE A, B, LMask
22845   //   RHS = VECTOR_SHUFFLE A, B, RMask
22846   // Check that the masks correspond to performing a horizontal operation.
22847   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22848     for (unsigned i = 0; i != NumLaneElts; ++i) {
22849       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22850
22851       // Ignore any UNDEF components.
22852       if (LIdx < 0 || RIdx < 0 ||
22853           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22854           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22855         continue;
22856
22857       // Check that successive elements are being operated on.  If not, this is
22858       // not a horizontal operation.
22859       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22860       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22861       if (!(LIdx == Index && RIdx == Index + 1) &&
22862           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22863         return false;
22864     }
22865   }
22866
22867   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22868   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22869   return true;
22870 }
22871
22872 /// Do target-specific dag combines on floating point adds.
22873 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22874                                   const X86Subtarget *Subtarget) {
22875   EVT VT = N->getValueType(0);
22876   SDValue LHS = N->getOperand(0);
22877   SDValue RHS = N->getOperand(1);
22878
22879   // Try to synthesize horizontal adds from adds of shuffles.
22880   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22881        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22882       isHorizontalBinOp(LHS, RHS, true))
22883     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22884   return SDValue();
22885 }
22886
22887 /// Do target-specific dag combines on floating point subs.
22888 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22889                                   const X86Subtarget *Subtarget) {
22890   EVT VT = N->getValueType(0);
22891   SDValue LHS = N->getOperand(0);
22892   SDValue RHS = N->getOperand(1);
22893
22894   // Try to synthesize horizontal subs from subs of shuffles.
22895   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22896        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22897       isHorizontalBinOp(LHS, RHS, false))
22898     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22899   return SDValue();
22900 }
22901
22902 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
22903 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22904   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22905
22906   // F[X]OR(0.0, x) -> x
22907   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22908     if (C->getValueAPF().isPosZero())
22909       return N->getOperand(1);
22910
22911   // F[X]OR(x, 0.0) -> x
22912   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22913     if (C->getValueAPF().isPosZero())
22914       return N->getOperand(0);
22915   return SDValue();
22916 }
22917
22918 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
22919 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22920   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22921
22922   // Only perform optimizations if UnsafeMath is used.
22923   if (!DAG.getTarget().Options.UnsafeFPMath)
22924     return SDValue();
22925
22926   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22927   // into FMINC and FMAXC, which are Commutative operations.
22928   unsigned NewOp = 0;
22929   switch (N->getOpcode()) {
22930     default: llvm_unreachable("unknown opcode");
22931     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22932     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22933   }
22934
22935   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22936                      N->getOperand(0), N->getOperand(1));
22937 }
22938
22939 /// Do target-specific dag combines on X86ISD::FAND nodes.
22940 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22941   // FAND(0.0, x) -> 0.0
22942   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22943     if (C->getValueAPF().isPosZero())
22944       return N->getOperand(0);
22945
22946   // FAND(x, 0.0) -> 0.0
22947   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22948     if (C->getValueAPF().isPosZero())
22949       return N->getOperand(1);
22950   
22951   return SDValue();
22952 }
22953
22954 /// Do target-specific dag combines on X86ISD::FANDN nodes
22955 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22956   // FANDN(0.0, x) -> x
22957   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22958     if (C->getValueAPF().isPosZero())
22959       return N->getOperand(1);
22960
22961   // FANDN(x, 0.0) -> 0.0
22962   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22963     if (C->getValueAPF().isPosZero())
22964       return N->getOperand(1);
22965
22966   return SDValue();
22967 }
22968
22969 static SDValue PerformBTCombine(SDNode *N,
22970                                 SelectionDAG &DAG,
22971                                 TargetLowering::DAGCombinerInfo &DCI) {
22972   // BT ignores high bits in the bit index operand.
22973   SDValue Op1 = N->getOperand(1);
22974   if (Op1.hasOneUse()) {
22975     unsigned BitWidth = Op1.getValueSizeInBits();
22976     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22977     APInt KnownZero, KnownOne;
22978     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22979                                           !DCI.isBeforeLegalizeOps());
22980     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22981     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22982         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22983       DCI.CommitTargetLoweringOpt(TLO);
22984   }
22985   return SDValue();
22986 }
22987
22988 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22989   SDValue Op = N->getOperand(0);
22990   if (Op.getOpcode() == ISD::BITCAST)
22991     Op = Op.getOperand(0);
22992   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22993   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22994       VT.getVectorElementType().getSizeInBits() ==
22995       OpVT.getVectorElementType().getSizeInBits()) {
22996     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22997   }
22998   return SDValue();
22999 }
23000
23001 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23002                                                const X86Subtarget *Subtarget) {
23003   EVT VT = N->getValueType(0);
23004   if (!VT.isVector())
23005     return SDValue();
23006
23007   SDValue N0 = N->getOperand(0);
23008   SDValue N1 = N->getOperand(1);
23009   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23010   SDLoc dl(N);
23011
23012   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23013   // both SSE and AVX2 since there is no sign-extended shift right
23014   // operation on a vector with 64-bit elements.
23015   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23016   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23017   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23018       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23019     SDValue N00 = N0.getOperand(0);
23020
23021     // EXTLOAD has a better solution on AVX2,
23022     // it may be replaced with X86ISD::VSEXT node.
23023     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23024       if (!ISD::isNormalLoad(N00.getNode()))
23025         return SDValue();
23026
23027     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23028         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23029                                   N00, N1);
23030       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23031     }
23032   }
23033   return SDValue();
23034 }
23035
23036 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23037                                   TargetLowering::DAGCombinerInfo &DCI,
23038                                   const X86Subtarget *Subtarget) {
23039   SDValue N0 = N->getOperand(0);
23040   EVT VT = N->getValueType(0);
23041
23042   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23043   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23044   // This exposes the sext to the sdivrem lowering, so that it directly extends
23045   // from AH (which we otherwise need to do contortions to access).
23046   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23047       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23048     SDLoc dl(N);
23049     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23050     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23051                             N0.getOperand(0), N0.getOperand(1));
23052     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23053     return R.getValue(1);
23054   }
23055
23056   if (!DCI.isBeforeLegalizeOps())
23057     return SDValue();
23058
23059   if (!Subtarget->hasFp256())
23060     return SDValue();
23061
23062   if (VT.isVector() && VT.getSizeInBits() == 256) {
23063     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23064     if (R.getNode())
23065       return R;
23066   }
23067
23068   return SDValue();
23069 }
23070
23071 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23072                                  const X86Subtarget* Subtarget) {
23073   SDLoc dl(N);
23074   EVT VT = N->getValueType(0);
23075
23076   // Let legalize expand this if it isn't a legal type yet.
23077   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23078     return SDValue();
23079
23080   EVT ScalarVT = VT.getScalarType();
23081   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23082       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23083     return SDValue();
23084
23085   SDValue A = N->getOperand(0);
23086   SDValue B = N->getOperand(1);
23087   SDValue C = N->getOperand(2);
23088
23089   bool NegA = (A.getOpcode() == ISD::FNEG);
23090   bool NegB = (B.getOpcode() == ISD::FNEG);
23091   bool NegC = (C.getOpcode() == ISD::FNEG);
23092
23093   // Negative multiplication when NegA xor NegB
23094   bool NegMul = (NegA != NegB);
23095   if (NegA)
23096     A = A.getOperand(0);
23097   if (NegB)
23098     B = B.getOperand(0);
23099   if (NegC)
23100     C = C.getOperand(0);
23101
23102   unsigned Opcode;
23103   if (!NegMul)
23104     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23105   else
23106     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23107
23108   return DAG.getNode(Opcode, dl, VT, A, B, C);
23109 }
23110
23111 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23112                                   TargetLowering::DAGCombinerInfo &DCI,
23113                                   const X86Subtarget *Subtarget) {
23114   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23115   //           (and (i32 x86isd::setcc_carry), 1)
23116   // This eliminates the zext. This transformation is necessary because
23117   // ISD::SETCC is always legalized to i8.
23118   SDLoc dl(N);
23119   SDValue N0 = N->getOperand(0);
23120   EVT VT = N->getValueType(0);
23121
23122   if (N0.getOpcode() == ISD::AND &&
23123       N0.hasOneUse() &&
23124       N0.getOperand(0).hasOneUse()) {
23125     SDValue N00 = N0.getOperand(0);
23126     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23127       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23128       if (!C || C->getZExtValue() != 1)
23129         return SDValue();
23130       return DAG.getNode(ISD::AND, dl, VT,
23131                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23132                                      N00.getOperand(0), N00.getOperand(1)),
23133                          DAG.getConstant(1, VT));
23134     }
23135   }
23136
23137   if (N0.getOpcode() == ISD::TRUNCATE &&
23138       N0.hasOneUse() &&
23139       N0.getOperand(0).hasOneUse()) {
23140     SDValue N00 = N0.getOperand(0);
23141     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23142       return DAG.getNode(ISD::AND, dl, VT,
23143                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23144                                      N00.getOperand(0), N00.getOperand(1)),
23145                          DAG.getConstant(1, VT));
23146     }
23147   }
23148   if (VT.is256BitVector()) {
23149     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23150     if (R.getNode())
23151       return R;
23152   }
23153
23154   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23155   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23156   // This exposes the zext to the udivrem lowering, so that it directly extends
23157   // from AH (which we otherwise need to do contortions to access).
23158   if (N0.getOpcode() == ISD::UDIVREM &&
23159       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23160       (VT == MVT::i32 || VT == MVT::i64)) {
23161     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23162     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23163                             N0.getOperand(0), N0.getOperand(1));
23164     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23165     return R.getValue(1);
23166   }
23167
23168   return SDValue();
23169 }
23170
23171 // Optimize x == -y --> x+y == 0
23172 //          x != -y --> x+y != 0
23173 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23174                                       const X86Subtarget* Subtarget) {
23175   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23176   SDValue LHS = N->getOperand(0);
23177   SDValue RHS = N->getOperand(1);
23178   EVT VT = N->getValueType(0);
23179   SDLoc DL(N);
23180
23181   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23182     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23183       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23184         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), LHS.getValueType(), RHS,
23185                                    LHS.getOperand(1));
23186         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23187                             DAG.getConstant(0, addV.getValueType()), CC);
23188       }
23189   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23190     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23191       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23192         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), RHS.getValueType(), LHS,
23193                                    RHS.getOperand(1));
23194         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23195                             DAG.getConstant(0, addV.getValueType()), CC);
23196       }
23197
23198   if (VT.getScalarType() == MVT::i1 &&
23199       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23200     bool IsSEXT0 =
23201         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23202         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23203     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23204
23205     if (!IsSEXT0 || !IsVZero1) {
23206       // Swap the operands and update the condition code.
23207       std::swap(LHS, RHS);
23208       CC = ISD::getSetCCSwappedOperands(CC);
23209
23210       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23211                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23212       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23213     }
23214
23215     if (IsSEXT0 && IsVZero1) {
23216       assert(VT == LHS.getOperand(0).getValueType() &&
23217              "Uexpected operand type");
23218       if (CC == ISD::SETGT)
23219         return DAG.getConstant(0, VT);
23220       if (CC == ISD::SETLE)
23221         return DAG.getConstant(1, VT);
23222       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23223         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23224       
23225       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23226              "Unexpected condition code!");
23227       return LHS.getOperand(0);
23228     }
23229   }
23230
23231   return SDValue();
23232 }
23233
23234 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23235                                          SelectionDAG &DAG) {
23236   SDLoc dl(Load);
23237   MVT VT = Load->getSimpleValueType(0);
23238   MVT EVT = VT.getVectorElementType();
23239   SDValue Addr = Load->getOperand(1);
23240   SDValue NewAddr = DAG.getNode(
23241       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23242       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23243
23244   SDValue NewLoad =
23245       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23246                   DAG.getMachineFunction().getMachineMemOperand(
23247                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23248   return NewLoad;
23249 }
23250
23251 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23252                                       const X86Subtarget *Subtarget) {
23253   SDLoc dl(N);
23254   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23255   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23256          "X86insertps is only defined for v4x32");
23257
23258   SDValue Ld = N->getOperand(1);
23259   if (MayFoldLoad(Ld)) {
23260     // Extract the countS bits from the immediate so we can get the proper
23261     // address when narrowing the vector load to a specific element.
23262     // When the second source op is a memory address, insertps doesn't use
23263     // countS and just gets an f32 from that address.
23264     unsigned DestIndex =
23265         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23266     
23267     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23268
23269     // Create this as a scalar to vector to match the instruction pattern.
23270     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23271     // countS bits are ignored when loading from memory on insertps, which
23272     // means we don't need to explicitly set them to 0.
23273     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23274                        LoadScalarToVector, N->getOperand(2));
23275   }
23276   return SDValue();
23277 }
23278
23279 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23280   SDValue V0 = N->getOperand(0);
23281   SDValue V1 = N->getOperand(1);
23282   SDLoc DL(N);
23283   EVT VT = N->getValueType(0);
23284
23285   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23286   // operands and changing the mask to 1. This saves us a bunch of
23287   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23288   // x86InstrInfo knows how to commute this back after instruction selection
23289   // if it would help register allocation.
23290   
23291   // TODO: If optimizing for size or a processor that doesn't suffer from
23292   // partial register update stalls, this should be transformed into a MOVSD
23293   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23294
23295   if (VT == MVT::v2f64)
23296     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23297       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23298         SDValue NewMask = DAG.getConstant(1, MVT::i8);
23299         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23300       }
23301
23302   return SDValue();
23303 }
23304
23305 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23306 // as "sbb reg,reg", since it can be extended without zext and produces
23307 // an all-ones bit which is more useful than 0/1 in some cases.
23308 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23309                                MVT VT) {
23310   if (VT == MVT::i8)
23311     return DAG.getNode(ISD::AND, DL, VT,
23312                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23313                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23314                        DAG.getConstant(1, VT));
23315   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23316   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23317                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23318                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23319 }
23320
23321 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23322 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23323                                    TargetLowering::DAGCombinerInfo &DCI,
23324                                    const X86Subtarget *Subtarget) {
23325   SDLoc DL(N);
23326   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23327   SDValue EFLAGS = N->getOperand(1);
23328
23329   if (CC == X86::COND_A) {
23330     // Try to convert COND_A into COND_B in an attempt to facilitate
23331     // materializing "setb reg".
23332     //
23333     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23334     // cannot take an immediate as its first operand.
23335     //
23336     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23337         EFLAGS.getValueType().isInteger() &&
23338         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23339       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23340                                    EFLAGS.getNode()->getVTList(),
23341                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23342       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23343       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23344     }
23345   }
23346
23347   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23348   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23349   // cases.
23350   if (CC == X86::COND_B)
23351     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23352
23353   SDValue Flags;
23354
23355   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23356   if (Flags.getNode()) {
23357     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23358     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23359   }
23360
23361   return SDValue();
23362 }
23363
23364 // Optimize branch condition evaluation.
23365 //
23366 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23367                                     TargetLowering::DAGCombinerInfo &DCI,
23368                                     const X86Subtarget *Subtarget) {
23369   SDLoc DL(N);
23370   SDValue Chain = N->getOperand(0);
23371   SDValue Dest = N->getOperand(1);
23372   SDValue EFLAGS = N->getOperand(3);
23373   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23374
23375   SDValue Flags;
23376
23377   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23378   if (Flags.getNode()) {
23379     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23380     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23381                        Flags);
23382   }
23383
23384   return SDValue();
23385 }
23386
23387 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23388                                                          SelectionDAG &DAG) {
23389   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23390   // optimize away operation when it's from a constant.
23391   //
23392   // The general transformation is:
23393   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23394   //       AND(VECTOR_CMP(x,y), constant2)
23395   //    constant2 = UNARYOP(constant)
23396
23397   // Early exit if this isn't a vector operation, the operand of the
23398   // unary operation isn't a bitwise AND, or if the sizes of the operations
23399   // aren't the same.
23400   EVT VT = N->getValueType(0);
23401   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23402       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23403       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23404     return SDValue();
23405
23406   // Now check that the other operand of the AND is a constant. We could
23407   // make the transformation for non-constant splats as well, but it's unclear
23408   // that would be a benefit as it would not eliminate any operations, just
23409   // perform one more step in scalar code before moving to the vector unit.
23410   if (BuildVectorSDNode *BV =
23411           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23412     // Bail out if the vector isn't a constant.
23413     if (!BV->isConstant())
23414       return SDValue();
23415
23416     // Everything checks out. Build up the new and improved node.
23417     SDLoc DL(N);
23418     EVT IntVT = BV->getValueType(0);
23419     // Create a new constant of the appropriate type for the transformed
23420     // DAG.
23421     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23422     // The AND node needs bitcasts to/from an integer vector type around it.
23423     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23424     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23425                                  N->getOperand(0)->getOperand(0), MaskConst);
23426     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23427     return Res;
23428   }
23429
23430   return SDValue();
23431 }
23432
23433 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23434                                         const X86Subtarget *Subtarget) {
23435   // First try to optimize away the conversion entirely when it's
23436   // conditionally from a constant. Vectors only.
23437   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23438   if (Res != SDValue())
23439     return Res;
23440
23441   // Now move on to more general possibilities.
23442   SDValue Op0 = N->getOperand(0);
23443   EVT InVT = Op0->getValueType(0);
23444
23445   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23446   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23447     SDLoc dl(N);
23448     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23449     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23450     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23451   }
23452
23453   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23454   // a 32-bit target where SSE doesn't support i64->FP operations.
23455   if (Op0.getOpcode() == ISD::LOAD) {
23456     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23457     EVT VT = Ld->getValueType(0);
23458     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23459         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23460         !Subtarget->is64Bit() && VT == MVT::i64) {
23461       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23462           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23463       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23464       return FILDChain;
23465     }
23466   }
23467   return SDValue();
23468 }
23469
23470 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23471 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23472                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23473   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23474   // the result is either zero or one (depending on the input carry bit).
23475   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23476   if (X86::isZeroNode(N->getOperand(0)) &&
23477       X86::isZeroNode(N->getOperand(1)) &&
23478       // We don't have a good way to replace an EFLAGS use, so only do this when
23479       // dead right now.
23480       SDValue(N, 1).use_empty()) {
23481     SDLoc DL(N);
23482     EVT VT = N->getValueType(0);
23483     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23484     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23485                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23486                                            DAG.getConstant(X86::COND_B,MVT::i8),
23487                                            N->getOperand(2)),
23488                                DAG.getConstant(1, VT));
23489     return DCI.CombineTo(N, Res1, CarryOut);
23490   }
23491
23492   return SDValue();
23493 }
23494
23495 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23496 //      (add Y, (setne X, 0)) -> sbb -1, Y
23497 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23498 //      (sub (setne X, 0), Y) -> adc -1, Y
23499 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23500   SDLoc DL(N);
23501
23502   // Look through ZExts.
23503   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23504   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23505     return SDValue();
23506
23507   SDValue SetCC = Ext.getOperand(0);
23508   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23509     return SDValue();
23510
23511   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23512   if (CC != X86::COND_E && CC != X86::COND_NE)
23513     return SDValue();
23514
23515   SDValue Cmp = SetCC.getOperand(1);
23516   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23517       !X86::isZeroNode(Cmp.getOperand(1)) ||
23518       !Cmp.getOperand(0).getValueType().isInteger())
23519     return SDValue();
23520
23521   SDValue CmpOp0 = Cmp.getOperand(0);
23522   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23523                                DAG.getConstant(1, CmpOp0.getValueType()));
23524
23525   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23526   if (CC == X86::COND_NE)
23527     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23528                        DL, OtherVal.getValueType(), OtherVal,
23529                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23530   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23531                      DL, OtherVal.getValueType(), OtherVal,
23532                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23533 }
23534
23535 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23536 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23537                                  const X86Subtarget *Subtarget) {
23538   EVT VT = N->getValueType(0);
23539   SDValue Op0 = N->getOperand(0);
23540   SDValue Op1 = N->getOperand(1);
23541
23542   // Try to synthesize horizontal adds from adds of shuffles.
23543   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23544        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23545       isHorizontalBinOp(Op0, Op1, true))
23546     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23547
23548   return OptimizeConditionalInDecrement(N, DAG);
23549 }
23550
23551 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23552                                  const X86Subtarget *Subtarget) {
23553   SDValue Op0 = N->getOperand(0);
23554   SDValue Op1 = N->getOperand(1);
23555
23556   // X86 can't encode an immediate LHS of a sub. See if we can push the
23557   // negation into a preceding instruction.
23558   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23559     // If the RHS of the sub is a XOR with one use and a constant, invert the
23560     // immediate. Then add one to the LHS of the sub so we can turn
23561     // X-Y -> X+~Y+1, saving one register.
23562     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23563         isa<ConstantSDNode>(Op1.getOperand(1))) {
23564       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23565       EVT VT = Op0.getValueType();
23566       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23567                                    Op1.getOperand(0),
23568                                    DAG.getConstant(~XorC, VT));
23569       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23570                          DAG.getConstant(C->getAPIntValue()+1, VT));
23571     }
23572   }
23573
23574   // Try to synthesize horizontal adds from adds of shuffles.
23575   EVT VT = N->getValueType(0);
23576   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23577        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23578       isHorizontalBinOp(Op0, Op1, true))
23579     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23580
23581   return OptimizeConditionalInDecrement(N, DAG);
23582 }
23583
23584 /// performVZEXTCombine - Performs build vector combines
23585 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23586                                    TargetLowering::DAGCombinerInfo &DCI,
23587                                    const X86Subtarget *Subtarget) {
23588   SDLoc DL(N);
23589   MVT VT = N->getSimpleValueType(0);
23590   SDValue Op = N->getOperand(0);
23591   MVT OpVT = Op.getSimpleValueType();
23592   MVT OpEltVT = OpVT.getVectorElementType();
23593   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23594
23595   // (vzext (bitcast (vzext (x)) -> (vzext x)
23596   SDValue V = Op;
23597   while (V.getOpcode() == ISD::BITCAST)
23598     V = V.getOperand(0);
23599
23600   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23601     MVT InnerVT = V.getSimpleValueType();
23602     MVT InnerEltVT = InnerVT.getVectorElementType();
23603
23604     // If the element sizes match exactly, we can just do one larger vzext. This
23605     // is always an exact type match as vzext operates on integer types.
23606     if (OpEltVT == InnerEltVT) {
23607       assert(OpVT == InnerVT && "Types must match for vzext!");
23608       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23609     }
23610
23611     // The only other way we can combine them is if only a single element of the
23612     // inner vzext is used in the input to the outer vzext.
23613     if (InnerEltVT.getSizeInBits() < InputBits)
23614       return SDValue();
23615
23616     // In this case, the inner vzext is completely dead because we're going to
23617     // only look at bits inside of the low element. Just do the outer vzext on
23618     // a bitcast of the input to the inner.
23619     return DAG.getNode(X86ISD::VZEXT, DL, VT,
23620                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23621   }
23622
23623   // Check if we can bypass extracting and re-inserting an element of an input
23624   // vector. Essentialy:
23625   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23626   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23627       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23628       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23629     SDValue ExtractedV = V.getOperand(0);
23630     SDValue OrigV = ExtractedV.getOperand(0);
23631     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23632       if (ExtractIdx->getZExtValue() == 0) {
23633         MVT OrigVT = OrigV.getSimpleValueType();
23634         // Extract a subvector if necessary...
23635         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23636           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23637           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23638                                     OrigVT.getVectorNumElements() / Ratio);
23639           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23640                               DAG.getIntPtrConstant(0));
23641         }
23642         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23643         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23644       }
23645   }
23646
23647   return SDValue();
23648 }
23649
23650 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23651                                              DAGCombinerInfo &DCI) const {
23652   SelectionDAG &DAG = DCI.DAG;
23653   switch (N->getOpcode()) {
23654   default: break;
23655   case ISD::EXTRACT_VECTOR_ELT:
23656     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23657   case ISD::VSELECT:
23658   case ISD::SELECT:
23659   case X86ISD::SHRUNKBLEND:
23660     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23661   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
23662   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23663   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23664   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23665   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23666   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23667   case ISD::SHL:
23668   case ISD::SRA:
23669   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23670   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23671   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23672   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23673   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23674   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23675   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23676   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
23677   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23678   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23679   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23680   case X86ISD::FXOR:
23681   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23682   case X86ISD::FMIN:
23683   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23684   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23685   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23686   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23687   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23688   case ISD::ANY_EXTEND:
23689   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23690   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23691   case ISD::SIGN_EXTEND_INREG:
23692     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23693   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23694   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23695   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23696   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23697   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23698   case X86ISD::SHUFP:       // Handle all target specific shuffles
23699   case X86ISD::PALIGNR:
23700   case X86ISD::UNPCKH:
23701   case X86ISD::UNPCKL:
23702   case X86ISD::MOVHLPS:
23703   case X86ISD::MOVLHPS:
23704   case X86ISD::PSHUFB:
23705   case X86ISD::PSHUFD:
23706   case X86ISD::PSHUFHW:
23707   case X86ISD::PSHUFLW:
23708   case X86ISD::MOVSS:
23709   case X86ISD::MOVSD:
23710   case X86ISD::VPERMILPI:
23711   case X86ISD::VPERM2X128:
23712   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23713   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23714   case ISD::INTRINSIC_WO_CHAIN:
23715     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23716   case X86ISD::INSERTPS: {
23717     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23718       return PerformINSERTPSCombine(N, DAG, Subtarget);
23719     break;
23720   }
23721   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
23722   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23723   }
23724
23725   return SDValue();
23726 }
23727
23728 /// isTypeDesirableForOp - Return true if the target has native support for
23729 /// the specified value type and it is 'desirable' to use the type for the
23730 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23731 /// instruction encodings are longer and some i16 instructions are slow.
23732 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23733   if (!isTypeLegal(VT))
23734     return false;
23735   if (VT != MVT::i16)
23736     return true;
23737
23738   switch (Opc) {
23739   default:
23740     return true;
23741   case ISD::LOAD:
23742   case ISD::SIGN_EXTEND:
23743   case ISD::ZERO_EXTEND:
23744   case ISD::ANY_EXTEND:
23745   case ISD::SHL:
23746   case ISD::SRL:
23747   case ISD::SUB:
23748   case ISD::ADD:
23749   case ISD::MUL:
23750   case ISD::AND:
23751   case ISD::OR:
23752   case ISD::XOR:
23753     return false;
23754   }
23755 }
23756
23757 /// IsDesirableToPromoteOp - This method query the target whether it is
23758 /// beneficial for dag combiner to promote the specified node. If true, it
23759 /// should return the desired promotion type by reference.
23760 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23761   EVT VT = Op.getValueType();
23762   if (VT != MVT::i16)
23763     return false;
23764
23765   bool Promote = false;
23766   bool Commute = false;
23767   switch (Op.getOpcode()) {
23768   default: break;
23769   case ISD::LOAD: {
23770     LoadSDNode *LD = cast<LoadSDNode>(Op);
23771     // If the non-extending load has a single use and it's not live out, then it
23772     // might be folded.
23773     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23774                                                      Op.hasOneUse()*/) {
23775       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23776              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23777         // The only case where we'd want to promote LOAD (rather then it being
23778         // promoted as an operand is when it's only use is liveout.
23779         if (UI->getOpcode() != ISD::CopyToReg)
23780           return false;
23781       }
23782     }
23783     Promote = true;
23784     break;
23785   }
23786   case ISD::SIGN_EXTEND:
23787   case ISD::ZERO_EXTEND:
23788   case ISD::ANY_EXTEND:
23789     Promote = true;
23790     break;
23791   case ISD::SHL:
23792   case ISD::SRL: {
23793     SDValue N0 = Op.getOperand(0);
23794     // Look out for (store (shl (load), x)).
23795     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23796       return false;
23797     Promote = true;
23798     break;
23799   }
23800   case ISD::ADD:
23801   case ISD::MUL:
23802   case ISD::AND:
23803   case ISD::OR:
23804   case ISD::XOR:
23805     Commute = true;
23806     // fallthrough
23807   case ISD::SUB: {
23808     SDValue N0 = Op.getOperand(0);
23809     SDValue N1 = Op.getOperand(1);
23810     if (!Commute && MayFoldLoad(N1))
23811       return false;
23812     // Avoid disabling potential load folding opportunities.
23813     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23814       return false;
23815     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23816       return false;
23817     Promote = true;
23818   }
23819   }
23820
23821   PVT = MVT::i32;
23822   return Promote;
23823 }
23824
23825 //===----------------------------------------------------------------------===//
23826 //                           X86 Inline Assembly Support
23827 //===----------------------------------------------------------------------===//
23828
23829 // Helper to match a string separated by whitespace.
23830 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
23831   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
23832
23833   for (StringRef Piece : Pieces) {
23834     if (!S.startswith(Piece)) // Check if the piece matches.
23835       return false;
23836
23837     S = S.substr(Piece.size());
23838     StringRef::size_type Pos = S.find_first_not_of(" \t");
23839     if (Pos == 0) // We matched a prefix.
23840       return false;
23841
23842     S = S.substr(Pos);
23843   }
23844
23845   return S.empty();
23846 }
23847
23848 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23849
23850   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23851     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23852         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23853         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23854
23855       if (AsmPieces.size() == 3)
23856         return true;
23857       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23858         return true;
23859     }
23860   }
23861   return false;
23862 }
23863
23864 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23865   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23866
23867   std::string AsmStr = IA->getAsmString();
23868
23869   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23870   if (!Ty || Ty->getBitWidth() % 16 != 0)
23871     return false;
23872
23873   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23874   SmallVector<StringRef, 4> AsmPieces;
23875   SplitString(AsmStr, AsmPieces, ";\n");
23876
23877   switch (AsmPieces.size()) {
23878   default: return false;
23879   case 1:
23880     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23881     // we will turn this bswap into something that will be lowered to logical
23882     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23883     // lower so don't worry about this.
23884     // bswap $0
23885     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
23886         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
23887         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
23888         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
23889         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
23890         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
23891       // No need to check constraints, nothing other than the equivalent of
23892       // "=r,0" would be valid here.
23893       return IntrinsicLowering::LowerToByteSwap(CI);
23894     }
23895
23896     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23897     if (CI->getType()->isIntegerTy(16) &&
23898         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23899         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
23900          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
23901       AsmPieces.clear();
23902       const std::string &ConstraintsStr = IA->getConstraintString();
23903       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23904       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23905       if (clobbersFlagRegisters(AsmPieces))
23906         return IntrinsicLowering::LowerToByteSwap(CI);
23907     }
23908     break;
23909   case 3:
23910     if (CI->getType()->isIntegerTy(32) &&
23911         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23912         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
23913         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
23914         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
23915       AsmPieces.clear();
23916       const std::string &ConstraintsStr = IA->getConstraintString();
23917       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23918       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23919       if (clobbersFlagRegisters(AsmPieces))
23920         return IntrinsicLowering::LowerToByteSwap(CI);
23921     }
23922
23923     if (CI->getType()->isIntegerTy(64)) {
23924       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23925       if (Constraints.size() >= 2 &&
23926           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23927           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23928         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23929         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
23930             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
23931             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
23932           return IntrinsicLowering::LowerToByteSwap(CI);
23933       }
23934     }
23935     break;
23936   }
23937   return false;
23938 }
23939
23940 /// getConstraintType - Given a constraint letter, return the type of
23941 /// constraint it is for this target.
23942 X86TargetLowering::ConstraintType
23943 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23944   if (Constraint.size() == 1) {
23945     switch (Constraint[0]) {
23946     case 'R':
23947     case 'q':
23948     case 'Q':
23949     case 'f':
23950     case 't':
23951     case 'u':
23952     case 'y':
23953     case 'x':
23954     case 'Y':
23955     case 'l':
23956       return C_RegisterClass;
23957     case 'a':
23958     case 'b':
23959     case 'c':
23960     case 'd':
23961     case 'S':
23962     case 'D':
23963     case 'A':
23964       return C_Register;
23965     case 'I':
23966     case 'J':
23967     case 'K':
23968     case 'L':
23969     case 'M':
23970     case 'N':
23971     case 'G':
23972     case 'C':
23973     case 'e':
23974     case 'Z':
23975       return C_Other;
23976     default:
23977       break;
23978     }
23979   }
23980   return TargetLowering::getConstraintType(Constraint);
23981 }
23982
23983 /// Examine constraint type and operand type and determine a weight value.
23984 /// This object must already have been set up with the operand type
23985 /// and the current alternative constraint selected.
23986 TargetLowering::ConstraintWeight
23987   X86TargetLowering::getSingleConstraintMatchWeight(
23988     AsmOperandInfo &info, const char *constraint) const {
23989   ConstraintWeight weight = CW_Invalid;
23990   Value *CallOperandVal = info.CallOperandVal;
23991     // If we don't have a value, we can't do a match,
23992     // but allow it at the lowest weight.
23993   if (!CallOperandVal)
23994     return CW_Default;
23995   Type *type = CallOperandVal->getType();
23996   // Look at the constraint type.
23997   switch (*constraint) {
23998   default:
23999     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24000   case 'R':
24001   case 'q':
24002   case 'Q':
24003   case 'a':
24004   case 'b':
24005   case 'c':
24006   case 'd':
24007   case 'S':
24008   case 'D':
24009   case 'A':
24010     if (CallOperandVal->getType()->isIntegerTy())
24011       weight = CW_SpecificReg;
24012     break;
24013   case 'f':
24014   case 't':
24015   case 'u':
24016     if (type->isFloatingPointTy())
24017       weight = CW_SpecificReg;
24018     break;
24019   case 'y':
24020     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24021       weight = CW_SpecificReg;
24022     break;
24023   case 'x':
24024   case 'Y':
24025     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24026         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24027       weight = CW_Register;
24028     break;
24029   case 'I':
24030     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24031       if (C->getZExtValue() <= 31)
24032         weight = CW_Constant;
24033     }
24034     break;
24035   case 'J':
24036     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24037       if (C->getZExtValue() <= 63)
24038         weight = CW_Constant;
24039     }
24040     break;
24041   case 'K':
24042     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24043       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24044         weight = CW_Constant;
24045     }
24046     break;
24047   case 'L':
24048     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24049       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24050         weight = CW_Constant;
24051     }
24052     break;
24053   case 'M':
24054     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24055       if (C->getZExtValue() <= 3)
24056         weight = CW_Constant;
24057     }
24058     break;
24059   case 'N':
24060     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24061       if (C->getZExtValue() <= 0xff)
24062         weight = CW_Constant;
24063     }
24064     break;
24065   case 'G':
24066   case 'C':
24067     if (dyn_cast<ConstantFP>(CallOperandVal)) {
24068       weight = CW_Constant;
24069     }
24070     break;
24071   case 'e':
24072     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24073       if ((C->getSExtValue() >= -0x80000000LL) &&
24074           (C->getSExtValue() <= 0x7fffffffLL))
24075         weight = CW_Constant;
24076     }
24077     break;
24078   case 'Z':
24079     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24080       if (C->getZExtValue() <= 0xffffffff)
24081         weight = CW_Constant;
24082     }
24083     break;
24084   }
24085   return weight;
24086 }
24087
24088 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24089 /// with another that has more specific requirements based on the type of the
24090 /// corresponding operand.
24091 const char *X86TargetLowering::
24092 LowerXConstraint(EVT ConstraintVT) const {
24093   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24094   // 'f' like normal targets.
24095   if (ConstraintVT.isFloatingPoint()) {
24096     if (Subtarget->hasSSE2())
24097       return "Y";
24098     if (Subtarget->hasSSE1())
24099       return "x";
24100   }
24101
24102   return TargetLowering::LowerXConstraint(ConstraintVT);
24103 }
24104
24105 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24106 /// vector.  If it is invalid, don't add anything to Ops.
24107 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24108                                                      std::string &Constraint,
24109                                                      std::vector<SDValue>&Ops,
24110                                                      SelectionDAG &DAG) const {
24111   SDValue Result;
24112
24113   // Only support length 1 constraints for now.
24114   if (Constraint.length() > 1) return;
24115
24116   char ConstraintLetter = Constraint[0];
24117   switch (ConstraintLetter) {
24118   default: break;
24119   case 'I':
24120     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24121       if (C->getZExtValue() <= 31) {
24122         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24123         break;
24124       }
24125     }
24126     return;
24127   case 'J':
24128     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24129       if (C->getZExtValue() <= 63) {
24130         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24131         break;
24132       }
24133     }
24134     return;
24135   case 'K':
24136     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24137       if (isInt<8>(C->getSExtValue())) {
24138         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24139         break;
24140       }
24141     }
24142     return;
24143   case 'L':
24144     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24145       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24146           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24147         Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24148         break;
24149       }
24150     }
24151     return;
24152   case 'M':
24153     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24154       if (C->getZExtValue() <= 3) {
24155         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24156         break;
24157       }
24158     }
24159     return;
24160   case 'N':
24161     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24162       if (C->getZExtValue() <= 255) {
24163         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24164         break;
24165       }
24166     }
24167     return;
24168   case 'O':
24169     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24170       if (C->getZExtValue() <= 127) {
24171         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24172         break;
24173       }
24174     }
24175     return;
24176   case 'e': {
24177     // 32-bit signed value
24178     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24179       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24180                                            C->getSExtValue())) {
24181         // Widen to 64 bits here to get it sign extended.
24182         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24183         break;
24184       }
24185     // FIXME gcc accepts some relocatable values here too, but only in certain
24186     // memory models; it's complicated.
24187     }
24188     return;
24189   }
24190   case 'Z': {
24191     // 32-bit unsigned value
24192     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24193       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24194                                            C->getZExtValue())) {
24195         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24196         break;
24197       }
24198     }
24199     // FIXME gcc accepts some relocatable values here too, but only in certain
24200     // memory models; it's complicated.
24201     return;
24202   }
24203   case 'i': {
24204     // Literal immediates are always ok.
24205     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24206       // Widen to 64 bits here to get it sign extended.
24207       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24208       break;
24209     }
24210
24211     // In any sort of PIC mode addresses need to be computed at runtime by
24212     // adding in a register or some sort of table lookup.  These can't
24213     // be used as immediates.
24214     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24215       return;
24216
24217     // If we are in non-pic codegen mode, we allow the address of a global (with
24218     // an optional displacement) to be used with 'i'.
24219     GlobalAddressSDNode *GA = nullptr;
24220     int64_t Offset = 0;
24221
24222     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24223     while (1) {
24224       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24225         Offset += GA->getOffset();
24226         break;
24227       } else if (Op.getOpcode() == ISD::ADD) {
24228         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24229           Offset += C->getZExtValue();
24230           Op = Op.getOperand(0);
24231           continue;
24232         }
24233       } else if (Op.getOpcode() == ISD::SUB) {
24234         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24235           Offset += -C->getZExtValue();
24236           Op = Op.getOperand(0);
24237           continue;
24238         }
24239       }
24240
24241       // Otherwise, this isn't something we can handle, reject it.
24242       return;
24243     }
24244
24245     const GlobalValue *GV = GA->getGlobal();
24246     // If we require an extra load to get this address, as in PIC mode, we
24247     // can't accept it.
24248     if (isGlobalStubReference(
24249             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24250       return;
24251
24252     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24253                                         GA->getValueType(0), Offset);
24254     break;
24255   }
24256   }
24257
24258   if (Result.getNode()) {
24259     Ops.push_back(Result);
24260     return;
24261   }
24262   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24263 }
24264
24265 std::pair<unsigned, const TargetRegisterClass *>
24266 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24267                                                 const std::string &Constraint,
24268                                                 MVT VT) const {
24269   // First, see if this is a constraint that directly corresponds to an LLVM
24270   // register class.
24271   if (Constraint.size() == 1) {
24272     // GCC Constraint Letters
24273     switch (Constraint[0]) {
24274     default: break;
24275       // TODO: Slight differences here in allocation order and leaving
24276       // RIP in the class. Do they matter any more here than they do
24277       // in the normal allocation?
24278     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24279       if (Subtarget->is64Bit()) {
24280         if (VT == MVT::i32 || VT == MVT::f32)
24281           return std::make_pair(0U, &X86::GR32RegClass);
24282         if (VT == MVT::i16)
24283           return std::make_pair(0U, &X86::GR16RegClass);
24284         if (VT == MVT::i8 || VT == MVT::i1)
24285           return std::make_pair(0U, &X86::GR8RegClass);
24286         if (VT == MVT::i64 || VT == MVT::f64)
24287           return std::make_pair(0U, &X86::GR64RegClass);
24288         break;
24289       }
24290       // 32-bit fallthrough
24291     case 'Q':   // Q_REGS
24292       if (VT == MVT::i32 || VT == MVT::f32)
24293         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24294       if (VT == MVT::i16)
24295         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24296       if (VT == MVT::i8 || VT == MVT::i1)
24297         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24298       if (VT == MVT::i64)
24299         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24300       break;
24301     case 'r':   // GENERAL_REGS
24302     case 'l':   // INDEX_REGS
24303       if (VT == MVT::i8 || VT == MVT::i1)
24304         return std::make_pair(0U, &X86::GR8RegClass);
24305       if (VT == MVT::i16)
24306         return std::make_pair(0U, &X86::GR16RegClass);
24307       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24308         return std::make_pair(0U, &X86::GR32RegClass);
24309       return std::make_pair(0U, &X86::GR64RegClass);
24310     case 'R':   // LEGACY_REGS
24311       if (VT == MVT::i8 || VT == MVT::i1)
24312         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24313       if (VT == MVT::i16)
24314         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24315       if (VT == MVT::i32 || !Subtarget->is64Bit())
24316         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24317       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24318     case 'f':  // FP Stack registers.
24319       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24320       // value to the correct fpstack register class.
24321       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24322         return std::make_pair(0U, &X86::RFP32RegClass);
24323       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24324         return std::make_pair(0U, &X86::RFP64RegClass);
24325       return std::make_pair(0U, &X86::RFP80RegClass);
24326     case 'y':   // MMX_REGS if MMX allowed.
24327       if (!Subtarget->hasMMX()) break;
24328       return std::make_pair(0U, &X86::VR64RegClass);
24329     case 'Y':   // SSE_REGS if SSE2 allowed
24330       if (!Subtarget->hasSSE2()) break;
24331       // FALL THROUGH.
24332     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24333       if (!Subtarget->hasSSE1()) break;
24334
24335       switch (VT.SimpleTy) {
24336       default: break;
24337       // Scalar SSE types.
24338       case MVT::f32:
24339       case MVT::i32:
24340         return std::make_pair(0U, &X86::FR32RegClass);
24341       case MVT::f64:
24342       case MVT::i64:
24343         return std::make_pair(0U, &X86::FR64RegClass);
24344       // Vector types.
24345       case MVT::v16i8:
24346       case MVT::v8i16:
24347       case MVT::v4i32:
24348       case MVT::v2i64:
24349       case MVT::v4f32:
24350       case MVT::v2f64:
24351         return std::make_pair(0U, &X86::VR128RegClass);
24352       // AVX types.
24353       case MVT::v32i8:
24354       case MVT::v16i16:
24355       case MVT::v8i32:
24356       case MVT::v4i64:
24357       case MVT::v8f32:
24358       case MVT::v4f64:
24359         return std::make_pair(0U, &X86::VR256RegClass);
24360       case MVT::v8f64:
24361       case MVT::v16f32:
24362       case MVT::v16i32:
24363       case MVT::v8i64:
24364         return std::make_pair(0U, &X86::VR512RegClass);
24365       }
24366       break;
24367     }
24368   }
24369
24370   // Use the default implementation in TargetLowering to convert the register
24371   // constraint into a member of a register class.
24372   std::pair<unsigned, const TargetRegisterClass*> Res;
24373   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24374
24375   // Not found as a standard register?
24376   if (!Res.second) {
24377     // Map st(0) -> st(7) -> ST0
24378     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24379         tolower(Constraint[1]) == 's' &&
24380         tolower(Constraint[2]) == 't' &&
24381         Constraint[3] == '(' &&
24382         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24383         Constraint[5] == ')' &&
24384         Constraint[6] == '}') {
24385
24386       Res.first = X86::FP0+Constraint[4]-'0';
24387       Res.second = &X86::RFP80RegClass;
24388       return Res;
24389     }
24390
24391     // GCC allows "st(0)" to be called just plain "st".
24392     if (StringRef("{st}").equals_lower(Constraint)) {
24393       Res.first = X86::FP0;
24394       Res.second = &X86::RFP80RegClass;
24395       return Res;
24396     }
24397
24398     // flags -> EFLAGS
24399     if (StringRef("{flags}").equals_lower(Constraint)) {
24400       Res.first = X86::EFLAGS;
24401       Res.second = &X86::CCRRegClass;
24402       return Res;
24403     }
24404
24405     // 'A' means EAX + EDX.
24406     if (Constraint == "A") {
24407       Res.first = X86::EAX;
24408       Res.second = &X86::GR32_ADRegClass;
24409       return Res;
24410     }
24411     return Res;
24412   }
24413
24414   // Otherwise, check to see if this is a register class of the wrong value
24415   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24416   // turn into {ax},{dx}.
24417   if (Res.second->hasType(VT))
24418     return Res;   // Correct type already, nothing to do.
24419
24420   // All of the single-register GCC register classes map their values onto
24421   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24422   // really want an 8-bit or 32-bit register, map to the appropriate register
24423   // class and return the appropriate register.
24424   if (Res.second == &X86::GR16RegClass) {
24425     if (VT == MVT::i8 || VT == MVT::i1) {
24426       unsigned DestReg = 0;
24427       switch (Res.first) {
24428       default: break;
24429       case X86::AX: DestReg = X86::AL; break;
24430       case X86::DX: DestReg = X86::DL; break;
24431       case X86::CX: DestReg = X86::CL; break;
24432       case X86::BX: DestReg = X86::BL; break;
24433       }
24434       if (DestReg) {
24435         Res.first = DestReg;
24436         Res.second = &X86::GR8RegClass;
24437       }
24438     } else if (VT == MVT::i32 || VT == MVT::f32) {
24439       unsigned DestReg = 0;
24440       switch (Res.first) {
24441       default: break;
24442       case X86::AX: DestReg = X86::EAX; break;
24443       case X86::DX: DestReg = X86::EDX; break;
24444       case X86::CX: DestReg = X86::ECX; break;
24445       case X86::BX: DestReg = X86::EBX; break;
24446       case X86::SI: DestReg = X86::ESI; break;
24447       case X86::DI: DestReg = X86::EDI; break;
24448       case X86::BP: DestReg = X86::EBP; break;
24449       case X86::SP: DestReg = X86::ESP; break;
24450       }
24451       if (DestReg) {
24452         Res.first = DestReg;
24453         Res.second = &X86::GR32RegClass;
24454       }
24455     } else if (VT == MVT::i64 || VT == MVT::f64) {
24456       unsigned DestReg = 0;
24457       switch (Res.first) {
24458       default: break;
24459       case X86::AX: DestReg = X86::RAX; break;
24460       case X86::DX: DestReg = X86::RDX; break;
24461       case X86::CX: DestReg = X86::RCX; break;
24462       case X86::BX: DestReg = X86::RBX; break;
24463       case X86::SI: DestReg = X86::RSI; break;
24464       case X86::DI: DestReg = X86::RDI; break;
24465       case X86::BP: DestReg = X86::RBP; break;
24466       case X86::SP: DestReg = X86::RSP; break;
24467       }
24468       if (DestReg) {
24469         Res.first = DestReg;
24470         Res.second = &X86::GR64RegClass;
24471       }
24472     }
24473   } else if (Res.second == &X86::FR32RegClass ||
24474              Res.second == &X86::FR64RegClass ||
24475              Res.second == &X86::VR128RegClass ||
24476              Res.second == &X86::VR256RegClass ||
24477              Res.second == &X86::FR32XRegClass ||
24478              Res.second == &X86::FR64XRegClass ||
24479              Res.second == &X86::VR128XRegClass ||
24480              Res.second == &X86::VR256XRegClass ||
24481              Res.second == &X86::VR512RegClass) {
24482     // Handle references to XMM physical registers that got mapped into the
24483     // wrong class.  This can happen with constraints like {xmm0} where the
24484     // target independent register mapper will just pick the first match it can
24485     // find, ignoring the required type.
24486
24487     if (VT == MVT::f32 || VT == MVT::i32)
24488       Res.second = &X86::FR32RegClass;
24489     else if (VT == MVT::f64 || VT == MVT::i64)
24490       Res.second = &X86::FR64RegClass;
24491     else if (X86::VR128RegClass.hasType(VT))
24492       Res.second = &X86::VR128RegClass;
24493     else if (X86::VR256RegClass.hasType(VT))
24494       Res.second = &X86::VR256RegClass;
24495     else if (X86::VR512RegClass.hasType(VT))
24496       Res.second = &X86::VR512RegClass;
24497   }
24498
24499   return Res;
24500 }
24501
24502 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24503                                             Type *Ty) const {
24504   // Scaling factors are not free at all.
24505   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24506   // will take 2 allocations in the out of order engine instead of 1
24507   // for plain addressing mode, i.e. inst (reg1).
24508   // E.g.,
24509   // vaddps (%rsi,%drx), %ymm0, %ymm1
24510   // Requires two allocations (one for the load, one for the computation)
24511   // whereas:
24512   // vaddps (%rsi), %ymm0, %ymm1
24513   // Requires just 1 allocation, i.e., freeing allocations for other operations
24514   // and having less micro operations to execute.
24515   //
24516   // For some X86 architectures, this is even worse because for instance for
24517   // stores, the complex addressing mode forces the instruction to use the
24518   // "load" ports instead of the dedicated "store" port.
24519   // E.g., on Haswell:
24520   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24521   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24522   if (isLegalAddressingMode(AM, Ty))
24523     // Scale represents reg2 * scale, thus account for 1
24524     // as soon as we use a second register.
24525     return AM.Scale != 0;
24526   return -1;
24527 }
24528
24529 bool X86TargetLowering::isTargetFTOL() const {
24530   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24531 }