Mutate TargetLowering::shouldExpandAtomicRMWInIR to specifically dictate how AtomicRM...
[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   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
874   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
875   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
876   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
877   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
878   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
879   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
880   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
881   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
882   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
883   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
884   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
885   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
886   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
887   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
888   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
889   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
890   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
891   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
892   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
893   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
894   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
895   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
896   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
897   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
898   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
899   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
900   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
901   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
902
903   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
904     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
905
906     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
907     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
908     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
909     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
910     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
911     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
912     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
913     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
914     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
915     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
916     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
917     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
919     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
920   }
921
922   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
923     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
924
925     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
926     // registers cannot be used even for integer operations.
927     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
928     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
929     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
930     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
931
932     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
933     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
934     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
935     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
936     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
937     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
938     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
939     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
940     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
941     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
942     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
943     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
944     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
945     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
946     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
947     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
948     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
952     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
953     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
954
955     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
956     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
959
960     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
961     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
965
966     // Only provide customized ctpop vector bit twiddling for vector types we
967     // know to perform better than using the popcnt instructions on each vector
968     // element. If popcnt isn't supported, always provide the custom version.
969     if (!Subtarget->hasPOPCNT()) {
970       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
971       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
972     }
973
974     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
975     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
976       MVT VT = (MVT::SimpleValueType)i;
977       // Do not attempt to custom lower non-power-of-2 vectors
978       if (!isPowerOf2_32(VT.getVectorNumElements()))
979         continue;
980       // Do not attempt to custom lower non-128-bit vectors
981       if (!VT.is128BitVector())
982         continue;
983       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
984       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
985       setOperationAction(ISD::VSELECT,            VT, Custom);
986       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
987     }
988
989     // We support custom legalizing of sext and anyext loads for specific
990     // memory vector types which we can load as a scalar (or sequence of
991     // scalars) and extend in-register to a legal 128-bit vector type. For sext
992     // loads these must work with a single scalar load.
993     for (MVT VT : MVT::integer_vector_valuetypes()) {
994       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
995       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
996       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
997       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
998       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
999       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
1000       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
1001       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
1002       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
1003     }
1004
1005     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1006     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1007     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1008     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1009     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1010     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1012     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1013
1014     if (Subtarget->is64Bit()) {
1015       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1016       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1017     }
1018
1019     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1020     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1021       MVT VT = (MVT::SimpleValueType)i;
1022
1023       // Do not attempt to promote non-128-bit vectors
1024       if (!VT.is128BitVector())
1025         continue;
1026
1027       setOperationAction(ISD::AND,    VT, Promote);
1028       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1029       setOperationAction(ISD::OR,     VT, Promote);
1030       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1031       setOperationAction(ISD::XOR,    VT, Promote);
1032       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1033       setOperationAction(ISD::LOAD,   VT, Promote);
1034       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1035       setOperationAction(ISD::SELECT, VT, Promote);
1036       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1037     }
1038
1039     // Custom lower v2i64 and v2f64 selects.
1040     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1042     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1043     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1044
1045     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1046     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1047
1048     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1049     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1050     // As there is no 64-bit GPR available, we need build a special custom
1051     // sequence to convert from v2i32 to v2f32.
1052     if (!Subtarget->is64Bit())
1053       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1054
1055     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1056     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1057
1058     for (MVT VT : MVT::fp_vector_valuetypes())
1059       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1060
1061     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1062     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1063     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1064   }
1065
1066   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1067     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1068     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1069     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1070     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1071     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1072     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1073     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1074     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1075     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1076     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1077
1078     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1079     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1080     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1081     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1082     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1083     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1084     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1085     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1086     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1087     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1088
1089     // FIXME: Do we need to handle scalar-to-vector here?
1090     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1091
1092     // We directly match byte blends in the backend as they match the VSELECT
1093     // condition form.
1094     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1095
1096     // SSE41 brings specific instructions for doing vector sign extend even in
1097     // cases where we don't have SRA.
1098     for (MVT VT : MVT::integer_vector_valuetypes()) {
1099       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1100       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1101       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1102     }
1103
1104     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1105     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1106     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1107     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1108     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1109     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1110     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1111
1112     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1113     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1114     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1115     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1116     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1117     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1118
1119     // i8 and i16 vectors are custom because the source register and source
1120     // source memory operand types are not the same width.  f32 vectors are
1121     // custom since the immediate controlling the insert encodes additional
1122     // information.
1123     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1124     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1125     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1126     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1127
1128     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1129     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1130     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1131     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1132
1133     // FIXME: these should be Legal, but that's only for the case where
1134     // the index is constant.  For now custom expand to deal with that.
1135     if (Subtarget->is64Bit()) {
1136       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1137       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1138     }
1139   }
1140
1141   if (Subtarget->hasSSE2()) {
1142     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1143     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1144
1145     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1146     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1147
1148     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1149     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1150
1151     // In the customized shift lowering, the legal cases in AVX2 will be
1152     // recognized.
1153     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1154     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1155
1156     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1157     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1158
1159     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1160   }
1161
1162   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1163     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1164     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1165     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1166     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1167     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1168     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1169
1170     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1171     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1172     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1173
1174     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1175     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1176     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1177     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1178     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1179     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1180     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1181     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1182     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1183     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1184     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1185     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1186
1187     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1188     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1189     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1190     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1191     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1192     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1193     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1194     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1195     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1196     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1197     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1198     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1199
1200     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1201     // even though v8i16 is a legal type.
1202     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1203     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1204     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1205
1206     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1207     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1208     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1209
1210     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1211     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1212
1213     for (MVT VT : MVT::fp_vector_valuetypes())
1214       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1215
1216     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1217     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1218
1219     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1220     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1221
1222     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1223     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1224
1225     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1226     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1227     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1228     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1229
1230     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1231     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1232     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1233
1234     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1235     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1236     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1237     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1238     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1239     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1240     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1241     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1242     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1243     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1244     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1245     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1246
1247     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1248       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1249       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1250       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1251       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1252       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1253       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1254     }
1255
1256     if (Subtarget->hasInt256()) {
1257       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1258       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1259       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1260       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1261
1262       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1263       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1264       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1265       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1266
1267       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1268       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1269       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1270       // Don't lower v32i8 because there is no 128-bit byte mul
1271
1272       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1273       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1274       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1275       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1276
1277       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1278       // when we have a 256bit-wide blend with immediate.
1279       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1280
1281       // Only provide customized ctpop vector bit twiddling for vector types we
1282       // know to perform better than using the popcnt instructions on each
1283       // vector element. If popcnt isn't supported, always provide the custom
1284       // version.
1285       if (!Subtarget->hasPOPCNT())
1286         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1287
1288       // Custom CTPOP always performs better on natively supported v8i32
1289       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1290
1291       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1292       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1293       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1294       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1295       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1296       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1297       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1298
1299       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1300       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1301       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1302       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1303       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1304       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1305     } else {
1306       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1307       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1308       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1309       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1310
1311       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1312       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1313       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1314       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1315
1316       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1317       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1318       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1319       // Don't lower v32i8 because there is no 128-bit byte mul
1320     }
1321
1322     // In the customized shift lowering, the legal cases in AVX2 will be
1323     // recognized.
1324     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1325     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1326
1327     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1328     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1329
1330     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1331
1332     // Custom lower several nodes for 256-bit types.
1333     for (MVT VT : MVT::vector_valuetypes()) {
1334       if (VT.getScalarSizeInBits() >= 32) {
1335         setOperationAction(ISD::MLOAD,  VT, Legal);
1336         setOperationAction(ISD::MSTORE, VT, Legal);
1337       }
1338       // Extract subvector is special because the value type
1339       // (result) is 128-bit but the source is 256-bit wide.
1340       if (VT.is128BitVector()) {
1341         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1342       }
1343       // Do not attempt to custom lower other non-256-bit vectors
1344       if (!VT.is256BitVector())
1345         continue;
1346
1347       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1348       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1349       setOperationAction(ISD::VSELECT,            VT, Custom);
1350       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1351       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1352       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1353       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1354       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1355     }
1356
1357     if (Subtarget->hasInt256())
1358       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1359
1360
1361     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1362     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1363       MVT VT = (MVT::SimpleValueType)i;
1364
1365       // Do not attempt to promote non-256-bit vectors
1366       if (!VT.is256BitVector())
1367         continue;
1368
1369       setOperationAction(ISD::AND,    VT, Promote);
1370       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1371       setOperationAction(ISD::OR,     VT, Promote);
1372       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1373       setOperationAction(ISD::XOR,    VT, Promote);
1374       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1375       setOperationAction(ISD::LOAD,   VT, Promote);
1376       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1377       setOperationAction(ISD::SELECT, VT, Promote);
1378       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1379     }
1380   }
1381
1382   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1383     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1384     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1385     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1386     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1387
1388     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1389     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1390     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1391
1392     for (MVT VT : MVT::fp_vector_valuetypes())
1393       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1394
1395     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1396     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1397     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1398     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1399     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1400     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1401     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1402     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1403     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1404     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1405
1406     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1407     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1408     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1409     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1410     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1411     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1412
1413     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1414     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1415     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1416     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1417     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1418     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1419     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1420     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1421
1422     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1423     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1424     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1425     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1426     if (Subtarget->is64Bit()) {
1427       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1428       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1429       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1430       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1431     }
1432     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1433     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1434     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1435     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1436     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1437     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1438     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1439     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1440     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1441     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1442     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1443     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1444     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1445     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1446
1447     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1448     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1449     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1450     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1451     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1452     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1453     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1454     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1455     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1456     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1457     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1458     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1459     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1460
1461     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1462     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1463     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1464     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1465     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1466     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1467     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1468     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1469     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1470     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1471
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1474     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1475     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1476     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1477     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1478
1479     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1480     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1481
1482     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1483
1484     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1485     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1486     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1487     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1488     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1489     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1490     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1491     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1492     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1493
1494     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1495     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1496
1497     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1498     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1499
1500     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1501
1502     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1503     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1504
1505     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1506     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1507
1508     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1509     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1510
1511     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1512     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1513     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1514     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1515     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1516     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1517
1518     if (Subtarget->hasCDI()) {
1519       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1520       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1521     }
1522
1523     // Custom lower several nodes.
1524     for (MVT VT : MVT::vector_valuetypes()) {
1525       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1526       // Extract subvector is special because the value type
1527       // (result) is 256/128-bit but the source is 512-bit wide.
1528       if (VT.is128BitVector() || VT.is256BitVector()) {
1529         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1530       }
1531       if (VT.getVectorElementType() == MVT::i1)
1532         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1533
1534       // Do not attempt to custom lower other non-512-bit vectors
1535       if (!VT.is512BitVector())
1536         continue;
1537
1538       if ( EltSize >= 32) {
1539         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1540         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1541         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1542         setOperationAction(ISD::VSELECT,             VT, Legal);
1543         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1544         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1545         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1546         setOperationAction(ISD::MLOAD,               VT, Legal);
1547         setOperationAction(ISD::MSTORE,              VT, Legal);
1548       }
1549     }
1550     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1551       MVT VT = (MVT::SimpleValueType)i;
1552
1553       // Do not attempt to promote non-512-bit vectors.
1554       if (!VT.is512BitVector())
1555         continue;
1556
1557       setOperationAction(ISD::SELECT, VT, Promote);
1558       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1559     }
1560   }// has  AVX-512
1561
1562   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1563     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1564     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1565
1566     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1567     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1568
1569     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1570     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1571     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1572     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1573     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1574     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1575     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1576     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1577     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1578
1579     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1580       const MVT VT = (MVT::SimpleValueType)i;
1581
1582       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1583
1584       // Do not attempt to promote non-512-bit vectors.
1585       if (!VT.is512BitVector())
1586         continue;
1587
1588       if (EltSize < 32) {
1589         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1590         setOperationAction(ISD::VSELECT,             VT, Legal);
1591       }
1592     }
1593   }
1594
1595   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1596     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1597     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1598
1599     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1600     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1601     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1602
1603     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1604     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1605     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1606     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1607     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1608     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1609   }
1610
1611   // We want to custom lower some of our intrinsics.
1612   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1613   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1614   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1615   if (!Subtarget->is64Bit())
1616     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1617
1618   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1619   // handle type legalization for these operations here.
1620   //
1621   // FIXME: We really should do custom legalization for addition and
1622   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1623   // than generic legalization for 64-bit multiplication-with-overflow, though.
1624   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1625     // Add/Sub/Mul with overflow operations are custom lowered.
1626     MVT VT = IntVTs[i];
1627     setOperationAction(ISD::SADDO, VT, Custom);
1628     setOperationAction(ISD::UADDO, VT, Custom);
1629     setOperationAction(ISD::SSUBO, VT, Custom);
1630     setOperationAction(ISD::USUBO, VT, Custom);
1631     setOperationAction(ISD::SMULO, VT, Custom);
1632     setOperationAction(ISD::UMULO, VT, Custom);
1633   }
1634
1635
1636   if (!Subtarget->is64Bit()) {
1637     // These libcalls are not available in 32-bit.
1638     setLibcallName(RTLIB::SHL_I128, nullptr);
1639     setLibcallName(RTLIB::SRL_I128, nullptr);
1640     setLibcallName(RTLIB::SRA_I128, nullptr);
1641   }
1642
1643   // Combine sin / cos into one node or libcall if possible.
1644   if (Subtarget->hasSinCos()) {
1645     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1646     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1647     if (Subtarget->isTargetDarwin()) {
1648       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1649       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1650       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1651       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1652     }
1653   }
1654
1655   if (Subtarget->isTargetWin64()) {
1656     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1657     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1658     setOperationAction(ISD::SREM, MVT::i128, Custom);
1659     setOperationAction(ISD::UREM, MVT::i128, Custom);
1660     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1661     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1662   }
1663
1664   // We have target-specific dag combine patterns for the following nodes:
1665   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1666   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1667   setTargetDAGCombine(ISD::BITCAST);
1668   setTargetDAGCombine(ISD::VSELECT);
1669   setTargetDAGCombine(ISD::SELECT);
1670   setTargetDAGCombine(ISD::SHL);
1671   setTargetDAGCombine(ISD::SRA);
1672   setTargetDAGCombine(ISD::SRL);
1673   setTargetDAGCombine(ISD::OR);
1674   setTargetDAGCombine(ISD::AND);
1675   setTargetDAGCombine(ISD::ADD);
1676   setTargetDAGCombine(ISD::FADD);
1677   setTargetDAGCombine(ISD::FSUB);
1678   setTargetDAGCombine(ISD::FMA);
1679   setTargetDAGCombine(ISD::SUB);
1680   setTargetDAGCombine(ISD::LOAD);
1681   setTargetDAGCombine(ISD::MLOAD);
1682   setTargetDAGCombine(ISD::STORE);
1683   setTargetDAGCombine(ISD::MSTORE);
1684   setTargetDAGCombine(ISD::ZERO_EXTEND);
1685   setTargetDAGCombine(ISD::ANY_EXTEND);
1686   setTargetDAGCombine(ISD::SIGN_EXTEND);
1687   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1688   setTargetDAGCombine(ISD::TRUNCATE);
1689   setTargetDAGCombine(ISD::SINT_TO_FP);
1690   setTargetDAGCombine(ISD::SETCC);
1691   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1692   setTargetDAGCombine(ISD::BUILD_VECTOR);
1693   setTargetDAGCombine(ISD::MUL);
1694   setTargetDAGCombine(ISD::XOR);
1695
1696   computeRegisterProperties(Subtarget->getRegisterInfo());
1697
1698   // On Darwin, -Os means optimize for size without hurting performance,
1699   // do not reduce the limit.
1700   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1701   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1702   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1703   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1704   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1705   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1706   setPrefLoopAlignment(4); // 2^4 bytes.
1707
1708   // Predictable cmov don't hurt on atom because it's in-order.
1709   PredictableSelectIsExpensive = !Subtarget->isAtom();
1710   EnableExtLdPromotion = true;
1711   setPrefFunctionAlignment(4); // 2^4 bytes.
1712
1713   verifyIntrinsicTables();
1714 }
1715
1716 // This has so far only been implemented for 64-bit MachO.
1717 bool X86TargetLowering::useLoadStackGuardNode() const {
1718   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1719 }
1720
1721 TargetLoweringBase::LegalizeTypeAction
1722 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1723   if (ExperimentalVectorWideningLegalization &&
1724       VT.getVectorNumElements() != 1 &&
1725       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1726     return TypeWidenVector;
1727
1728   return TargetLoweringBase::getPreferredVectorAction(VT);
1729 }
1730
1731 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1732   if (!VT.isVector())
1733     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1734
1735   const unsigned NumElts = VT.getVectorNumElements();
1736   const EVT EltVT = VT.getVectorElementType();
1737   if (VT.is512BitVector()) {
1738     if (Subtarget->hasAVX512())
1739       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1740           EltVT == MVT::f32 || EltVT == MVT::f64)
1741         switch(NumElts) {
1742         case  8: return MVT::v8i1;
1743         case 16: return MVT::v16i1;
1744       }
1745     if (Subtarget->hasBWI())
1746       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1747         switch(NumElts) {
1748         case 32: return MVT::v32i1;
1749         case 64: return MVT::v64i1;
1750       }
1751   }
1752
1753   if (VT.is256BitVector() || VT.is128BitVector()) {
1754     if (Subtarget->hasVLX())
1755       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1756           EltVT == MVT::f32 || EltVT == MVT::f64)
1757         switch(NumElts) {
1758         case 2: return MVT::v2i1;
1759         case 4: return MVT::v4i1;
1760         case 8: return MVT::v8i1;
1761       }
1762     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1763       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1764         switch(NumElts) {
1765         case  8: return MVT::v8i1;
1766         case 16: return MVT::v16i1;
1767         case 32: return MVT::v32i1;
1768       }
1769   }
1770
1771   return VT.changeVectorElementTypeToInteger();
1772 }
1773
1774 /// Helper for getByValTypeAlignment to determine
1775 /// the desired ByVal argument alignment.
1776 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1777   if (MaxAlign == 16)
1778     return;
1779   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1780     if (VTy->getBitWidth() == 128)
1781       MaxAlign = 16;
1782   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1783     unsigned EltAlign = 0;
1784     getMaxByValAlign(ATy->getElementType(), EltAlign);
1785     if (EltAlign > MaxAlign)
1786       MaxAlign = EltAlign;
1787   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1788     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1789       unsigned EltAlign = 0;
1790       getMaxByValAlign(STy->getElementType(i), EltAlign);
1791       if (EltAlign > MaxAlign)
1792         MaxAlign = EltAlign;
1793       if (MaxAlign == 16)
1794         break;
1795     }
1796   }
1797 }
1798
1799 /// Return the desired alignment for ByVal aggregate
1800 /// function arguments in the caller parameter area. For X86, aggregates
1801 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1802 /// are at 4-byte boundaries.
1803 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1804   if (Subtarget->is64Bit()) {
1805     // Max of 8 and alignment of type.
1806     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1807     if (TyAlign > 8)
1808       return TyAlign;
1809     return 8;
1810   }
1811
1812   unsigned Align = 4;
1813   if (Subtarget->hasSSE1())
1814     getMaxByValAlign(Ty, Align);
1815   return Align;
1816 }
1817
1818 /// Returns the target specific optimal type for load
1819 /// and store operations as a result of memset, memcpy, and memmove
1820 /// lowering. If DstAlign is zero that means it's safe to destination
1821 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1822 /// means there isn't a need to check it against alignment requirement,
1823 /// probably because the source does not need to be loaded. If 'IsMemset' is
1824 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1825 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1826 /// source is constant so it does not need to be loaded.
1827 /// It returns EVT::Other if the type should be determined using generic
1828 /// target-independent logic.
1829 EVT
1830 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1831                                        unsigned DstAlign, unsigned SrcAlign,
1832                                        bool IsMemset, bool ZeroMemset,
1833                                        bool MemcpyStrSrc,
1834                                        MachineFunction &MF) const {
1835   const Function *F = MF.getFunction();
1836   if ((!IsMemset || ZeroMemset) &&
1837       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1838     if (Size >= 16 &&
1839         (Subtarget->isUnalignedMemAccessFast() ||
1840          ((DstAlign == 0 || DstAlign >= 16) &&
1841           (SrcAlign == 0 || SrcAlign >= 16)))) {
1842       if (Size >= 32) {
1843         if (Subtarget->hasInt256())
1844           return MVT::v8i32;
1845         if (Subtarget->hasFp256())
1846           return MVT::v8f32;
1847       }
1848       if (Subtarget->hasSSE2())
1849         return MVT::v4i32;
1850       if (Subtarget->hasSSE1())
1851         return MVT::v4f32;
1852     } else if (!MemcpyStrSrc && Size >= 8 &&
1853                !Subtarget->is64Bit() &&
1854                Subtarget->hasSSE2()) {
1855       // Do not use f64 to lower memcpy if source is string constant. It's
1856       // better to use i32 to avoid the loads.
1857       return MVT::f64;
1858     }
1859   }
1860   if (Subtarget->is64Bit() && Size >= 8)
1861     return MVT::i64;
1862   return MVT::i32;
1863 }
1864
1865 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1866   if (VT == MVT::f32)
1867     return X86ScalarSSEf32;
1868   else if (VT == MVT::f64)
1869     return X86ScalarSSEf64;
1870   return true;
1871 }
1872
1873 bool
1874 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1875                                                   unsigned,
1876                                                   unsigned,
1877                                                   bool *Fast) const {
1878   if (Fast)
1879     *Fast = Subtarget->isUnalignedMemAccessFast();
1880   return true;
1881 }
1882
1883 /// Return the entry encoding for a jump table in the
1884 /// current function.  The returned value is a member of the
1885 /// MachineJumpTableInfo::JTEntryKind enum.
1886 unsigned X86TargetLowering::getJumpTableEncoding() const {
1887   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1888   // symbol.
1889   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1890       Subtarget->isPICStyleGOT())
1891     return MachineJumpTableInfo::EK_Custom32;
1892
1893   // Otherwise, use the normal jump table encoding heuristics.
1894   return TargetLowering::getJumpTableEncoding();
1895 }
1896
1897 const MCExpr *
1898 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1899                                              const MachineBasicBlock *MBB,
1900                                              unsigned uid,MCContext &Ctx) const{
1901   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1902          Subtarget->isPICStyleGOT());
1903   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1904   // entries.
1905   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1906                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1907 }
1908
1909 /// Returns relocation base for the given PIC jumptable.
1910 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1911                                                     SelectionDAG &DAG) const {
1912   if (!Subtarget->is64Bit())
1913     // This doesn't have SDLoc associated with it, but is not really the
1914     // same as a Register.
1915     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1916   return Table;
1917 }
1918
1919 /// This returns the relocation base for the given PIC jumptable,
1920 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1921 const MCExpr *X86TargetLowering::
1922 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1923                              MCContext &Ctx) const {
1924   // X86-64 uses RIP relative addressing based on the jump table label.
1925   if (Subtarget->isPICStyleRIPRel())
1926     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1927
1928   // Otherwise, the reference is relative to the PIC base.
1929   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1930 }
1931
1932 std::pair<const TargetRegisterClass *, uint8_t>
1933 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1934                                            MVT VT) const {
1935   const TargetRegisterClass *RRC = nullptr;
1936   uint8_t Cost = 1;
1937   switch (VT.SimpleTy) {
1938   default:
1939     return TargetLowering::findRepresentativeClass(TRI, VT);
1940   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1941     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1942     break;
1943   case MVT::x86mmx:
1944     RRC = &X86::VR64RegClass;
1945     break;
1946   case MVT::f32: case MVT::f64:
1947   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1948   case MVT::v4f32: case MVT::v2f64:
1949   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1950   case MVT::v4f64:
1951     RRC = &X86::VR128RegClass;
1952     break;
1953   }
1954   return std::make_pair(RRC, Cost);
1955 }
1956
1957 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1958                                                unsigned &Offset) const {
1959   if (!Subtarget->isTargetLinux())
1960     return false;
1961
1962   if (Subtarget->is64Bit()) {
1963     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1964     Offset = 0x28;
1965     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1966       AddressSpace = 256;
1967     else
1968       AddressSpace = 257;
1969   } else {
1970     // %gs:0x14 on i386
1971     Offset = 0x14;
1972     AddressSpace = 256;
1973   }
1974   return true;
1975 }
1976
1977 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1978                                             unsigned DestAS) const {
1979   assert(SrcAS != DestAS && "Expected different address spaces!");
1980
1981   return SrcAS < 256 && DestAS < 256;
1982 }
1983
1984 //===----------------------------------------------------------------------===//
1985 //               Return Value Calling Convention Implementation
1986 //===----------------------------------------------------------------------===//
1987
1988 #include "X86GenCallingConv.inc"
1989
1990 bool
1991 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1992                                   MachineFunction &MF, bool isVarArg,
1993                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1994                         LLVMContext &Context) const {
1995   SmallVector<CCValAssign, 16> RVLocs;
1996   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1997   return CCInfo.CheckReturn(Outs, RetCC_X86);
1998 }
1999
2000 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2001   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2002   return ScratchRegs;
2003 }
2004
2005 SDValue
2006 X86TargetLowering::LowerReturn(SDValue Chain,
2007                                CallingConv::ID CallConv, bool isVarArg,
2008                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2009                                const SmallVectorImpl<SDValue> &OutVals,
2010                                SDLoc dl, SelectionDAG &DAG) const {
2011   MachineFunction &MF = DAG.getMachineFunction();
2012   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2013
2014   SmallVector<CCValAssign, 16> RVLocs;
2015   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2016   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2017
2018   SDValue Flag;
2019   SmallVector<SDValue, 6> RetOps;
2020   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2021   // Operand #1 = Bytes To Pop
2022   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2023                    MVT::i16));
2024
2025   // Copy the result values into the output registers.
2026   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2027     CCValAssign &VA = RVLocs[i];
2028     assert(VA.isRegLoc() && "Can only return in registers!");
2029     SDValue ValToCopy = OutVals[i];
2030     EVT ValVT = ValToCopy.getValueType();
2031
2032     // Promote values to the appropriate types.
2033     if (VA.getLocInfo() == CCValAssign::SExt)
2034       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2035     else if (VA.getLocInfo() == CCValAssign::ZExt)
2036       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2037     else if (VA.getLocInfo() == CCValAssign::AExt)
2038       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2039     else if (VA.getLocInfo() == CCValAssign::BCvt)
2040       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2041
2042     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2043            "Unexpected FP-extend for return value.");
2044
2045     // If this is x86-64, and we disabled SSE, we can't return FP values,
2046     // or SSE or MMX vectors.
2047     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2048          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2049           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2050       report_fatal_error("SSE register return with SSE disabled");
2051     }
2052     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2053     // llvm-gcc has never done it right and no one has noticed, so this
2054     // should be OK for now.
2055     if (ValVT == MVT::f64 &&
2056         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2057       report_fatal_error("SSE2 register return with SSE2 disabled");
2058
2059     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2060     // the RET instruction and handled by the FP Stackifier.
2061     if (VA.getLocReg() == X86::FP0 ||
2062         VA.getLocReg() == X86::FP1) {
2063       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2064       // change the value to the FP stack register class.
2065       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2066         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2067       RetOps.push_back(ValToCopy);
2068       // Don't emit a copytoreg.
2069       continue;
2070     }
2071
2072     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2073     // which is returned in RAX / RDX.
2074     if (Subtarget->is64Bit()) {
2075       if (ValVT == MVT::x86mmx) {
2076         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2077           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2078           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2079                                   ValToCopy);
2080           // If we don't have SSE2 available, convert to v4f32 so the generated
2081           // register is legal.
2082           if (!Subtarget->hasSSE2())
2083             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2084         }
2085       }
2086     }
2087
2088     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2089     Flag = Chain.getValue(1);
2090     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2091   }
2092
2093   // The x86-64 ABIs require that for returning structs by value we copy
2094   // the sret argument into %rax/%eax (depending on ABI) for the return.
2095   // Win32 requires us to put the sret argument to %eax as well.
2096   // We saved the argument into a virtual register in the entry block,
2097   // so now we copy the value out and into %rax/%eax.
2098   //
2099   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2100   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2101   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2102   // either case FuncInfo->setSRetReturnReg() will have been called.
2103   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2104     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2105            "No need for an sret register");
2106     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2107
2108     unsigned RetValReg
2109         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2110           X86::RAX : X86::EAX;
2111     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2112     Flag = Chain.getValue(1);
2113
2114     // RAX/EAX now acts like a return value.
2115     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2116   }
2117
2118   RetOps[0] = Chain;  // Update chain.
2119
2120   // Add the flag if we have it.
2121   if (Flag.getNode())
2122     RetOps.push_back(Flag);
2123
2124   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2125 }
2126
2127 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2128   if (N->getNumValues() != 1)
2129     return false;
2130   if (!N->hasNUsesOfValue(1, 0))
2131     return false;
2132
2133   SDValue TCChain = Chain;
2134   SDNode *Copy = *N->use_begin();
2135   if (Copy->getOpcode() == ISD::CopyToReg) {
2136     // If the copy has a glue operand, we conservatively assume it isn't safe to
2137     // perform a tail call.
2138     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2139       return false;
2140     TCChain = Copy->getOperand(0);
2141   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2142     return false;
2143
2144   bool HasRet = false;
2145   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2146        UI != UE; ++UI) {
2147     if (UI->getOpcode() != X86ISD::RET_FLAG)
2148       return false;
2149     // If we are returning more than one value, we can definitely
2150     // not make a tail call see PR19530
2151     if (UI->getNumOperands() > 4)
2152       return false;
2153     if (UI->getNumOperands() == 4 &&
2154         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2155       return false;
2156     HasRet = true;
2157   }
2158
2159   if (!HasRet)
2160     return false;
2161
2162   Chain = TCChain;
2163   return true;
2164 }
2165
2166 EVT
2167 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2168                                             ISD::NodeType ExtendKind) const {
2169   MVT ReturnMVT;
2170   // TODO: Is this also valid on 32-bit?
2171   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2172     ReturnMVT = MVT::i8;
2173   else
2174     ReturnMVT = MVT::i32;
2175
2176   EVT MinVT = getRegisterType(Context, ReturnMVT);
2177   return VT.bitsLT(MinVT) ? MinVT : VT;
2178 }
2179
2180 /// Lower the result values of a call into the
2181 /// appropriate copies out of appropriate physical registers.
2182 ///
2183 SDValue
2184 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2185                                    CallingConv::ID CallConv, bool isVarArg,
2186                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2187                                    SDLoc dl, SelectionDAG &DAG,
2188                                    SmallVectorImpl<SDValue> &InVals) const {
2189
2190   // Assign locations to each value returned by this call.
2191   SmallVector<CCValAssign, 16> RVLocs;
2192   bool Is64Bit = Subtarget->is64Bit();
2193   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2194                  *DAG.getContext());
2195   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2196
2197   // Copy all of the result registers out of their specified physreg.
2198   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2199     CCValAssign &VA = RVLocs[i];
2200     EVT CopyVT = VA.getValVT();
2201
2202     // If this is x86-64, and we disabled SSE, we can't return FP values
2203     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2204         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2205       report_fatal_error("SSE register return with SSE disabled");
2206     }
2207
2208     // If we prefer to use the value in xmm registers, copy it out as f80 and
2209     // use a truncate to move it from fp stack reg to xmm reg.
2210     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2211         isScalarFPTypeInSSEReg(VA.getValVT()))
2212       CopyVT = MVT::f80;
2213
2214     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2215                                CopyVT, InFlag).getValue(1);
2216     SDValue Val = Chain.getValue(0);
2217
2218     if (CopyVT != VA.getValVT())
2219       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2220                         // This truncation won't change the value.
2221                         DAG.getIntPtrConstant(1));
2222
2223     InFlag = Chain.getValue(2);
2224     InVals.push_back(Val);
2225   }
2226
2227   return Chain;
2228 }
2229
2230 //===----------------------------------------------------------------------===//
2231 //                C & StdCall & Fast Calling Convention implementation
2232 //===----------------------------------------------------------------------===//
2233 //  StdCall calling convention seems to be standard for many Windows' API
2234 //  routines and around. It differs from C calling convention just a little:
2235 //  callee should clean up the stack, not caller. Symbols should be also
2236 //  decorated in some fancy way :) It doesn't support any vector arguments.
2237 //  For info on fast calling convention see Fast Calling Convention (tail call)
2238 //  implementation LowerX86_32FastCCCallTo.
2239
2240 /// CallIsStructReturn - Determines whether a call uses struct return
2241 /// semantics.
2242 enum StructReturnType {
2243   NotStructReturn,
2244   RegStructReturn,
2245   StackStructReturn
2246 };
2247 static StructReturnType
2248 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2249   if (Outs.empty())
2250     return NotStructReturn;
2251
2252   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2253   if (!Flags.isSRet())
2254     return NotStructReturn;
2255   if (Flags.isInReg())
2256     return RegStructReturn;
2257   return StackStructReturn;
2258 }
2259
2260 /// Determines whether a function uses struct return semantics.
2261 static StructReturnType
2262 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2263   if (Ins.empty())
2264     return NotStructReturn;
2265
2266   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2267   if (!Flags.isSRet())
2268     return NotStructReturn;
2269   if (Flags.isInReg())
2270     return RegStructReturn;
2271   return StackStructReturn;
2272 }
2273
2274 /// Make a copy of an aggregate at address specified by "Src" to address
2275 /// "Dst" with size and alignment information specified by the specific
2276 /// parameter attribute. The copy will be passed as a byval function parameter.
2277 static SDValue
2278 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2279                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2280                           SDLoc dl) {
2281   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2282
2283   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2284                        /*isVolatile*/false, /*AlwaysInline=*/true,
2285                        MachinePointerInfo(), MachinePointerInfo());
2286 }
2287
2288 /// Return true if the calling convention is one that
2289 /// supports tail call optimization.
2290 static bool IsTailCallConvention(CallingConv::ID CC) {
2291   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2292           CC == CallingConv::HiPE);
2293 }
2294
2295 /// \brief Return true if the calling convention is a C calling convention.
2296 static bool IsCCallConvention(CallingConv::ID CC) {
2297   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2298           CC == CallingConv::X86_64_SysV);
2299 }
2300
2301 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2302   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2303     return false;
2304
2305   CallSite CS(CI);
2306   CallingConv::ID CalleeCC = CS.getCallingConv();
2307   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2308     return false;
2309
2310   return true;
2311 }
2312
2313 /// Return true if the function is being made into
2314 /// a tailcall target by changing its ABI.
2315 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2316                                    bool GuaranteedTailCallOpt) {
2317   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2318 }
2319
2320 SDValue
2321 X86TargetLowering::LowerMemArgument(SDValue Chain,
2322                                     CallingConv::ID CallConv,
2323                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2324                                     SDLoc dl, SelectionDAG &DAG,
2325                                     const CCValAssign &VA,
2326                                     MachineFrameInfo *MFI,
2327                                     unsigned i) const {
2328   // Create the nodes corresponding to a load from this parameter slot.
2329   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2330   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2331       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2332   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2333   EVT ValVT;
2334
2335   // If value is passed by pointer we have address passed instead of the value
2336   // itself.
2337   if (VA.getLocInfo() == CCValAssign::Indirect)
2338     ValVT = VA.getLocVT();
2339   else
2340     ValVT = VA.getValVT();
2341
2342   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2343   // changed with more analysis.
2344   // In case of tail call optimization mark all arguments mutable. Since they
2345   // could be overwritten by lowering of arguments in case of a tail call.
2346   if (Flags.isByVal()) {
2347     unsigned Bytes = Flags.getByValSize();
2348     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2349     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2350     return DAG.getFrameIndex(FI, getPointerTy());
2351   } else {
2352     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2353                                     VA.getLocMemOffset(), isImmutable);
2354     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2355     return DAG.getLoad(ValVT, dl, Chain, FIN,
2356                        MachinePointerInfo::getFixedStack(FI),
2357                        false, false, false, 0);
2358   }
2359 }
2360
2361 // FIXME: Get this from tablegen.
2362 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2363                                                 const X86Subtarget *Subtarget) {
2364   assert(Subtarget->is64Bit());
2365
2366   if (Subtarget->isCallingConvWin64(CallConv)) {
2367     static const MCPhysReg GPR64ArgRegsWin64[] = {
2368       X86::RCX, X86::RDX, X86::R8,  X86::R9
2369     };
2370     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2371   }
2372
2373   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2374     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2375   };
2376   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2377 }
2378
2379 // FIXME: Get this from tablegen.
2380 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2381                                                 CallingConv::ID CallConv,
2382                                                 const X86Subtarget *Subtarget) {
2383   assert(Subtarget->is64Bit());
2384   if (Subtarget->isCallingConvWin64(CallConv)) {
2385     // The XMM registers which might contain var arg parameters are shadowed
2386     // in their paired GPR.  So we only need to save the GPR to their home
2387     // slots.
2388     // TODO: __vectorcall will change this.
2389     return None;
2390   }
2391
2392   const Function *Fn = MF.getFunction();
2393   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2394   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2395          "SSE register cannot be used when SSE is disabled!");
2396   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2397       !Subtarget->hasSSE1())
2398     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2399     // registers.
2400     return None;
2401
2402   static const MCPhysReg XMMArgRegs64Bit[] = {
2403     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2404     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2405   };
2406   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2407 }
2408
2409 SDValue
2410 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2411                                         CallingConv::ID CallConv,
2412                                         bool isVarArg,
2413                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2414                                         SDLoc dl,
2415                                         SelectionDAG &DAG,
2416                                         SmallVectorImpl<SDValue> &InVals)
2417                                           const {
2418   MachineFunction &MF = DAG.getMachineFunction();
2419   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2420
2421   const Function* Fn = MF.getFunction();
2422   if (Fn->hasExternalLinkage() &&
2423       Subtarget->isTargetCygMing() &&
2424       Fn->getName() == "main")
2425     FuncInfo->setForceFramePointer(true);
2426
2427   MachineFrameInfo *MFI = MF.getFrameInfo();
2428   bool Is64Bit = Subtarget->is64Bit();
2429   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2430
2431   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2432          "Var args not supported with calling convention fastcc, ghc or hipe");
2433
2434   // Assign locations to all of the incoming arguments.
2435   SmallVector<CCValAssign, 16> ArgLocs;
2436   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2437
2438   // Allocate shadow area for Win64
2439   if (IsWin64)
2440     CCInfo.AllocateStack(32, 8);
2441
2442   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2443
2444   unsigned LastVal = ~0U;
2445   SDValue ArgValue;
2446   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2447     CCValAssign &VA = ArgLocs[i];
2448     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2449     // places.
2450     assert(VA.getValNo() != LastVal &&
2451            "Don't support value assigned to multiple locs yet");
2452     (void)LastVal;
2453     LastVal = VA.getValNo();
2454
2455     if (VA.isRegLoc()) {
2456       EVT RegVT = VA.getLocVT();
2457       const TargetRegisterClass *RC;
2458       if (RegVT == MVT::i32)
2459         RC = &X86::GR32RegClass;
2460       else if (Is64Bit && RegVT == MVT::i64)
2461         RC = &X86::GR64RegClass;
2462       else if (RegVT == MVT::f32)
2463         RC = &X86::FR32RegClass;
2464       else if (RegVT == MVT::f64)
2465         RC = &X86::FR64RegClass;
2466       else if (RegVT.is512BitVector())
2467         RC = &X86::VR512RegClass;
2468       else if (RegVT.is256BitVector())
2469         RC = &X86::VR256RegClass;
2470       else if (RegVT.is128BitVector())
2471         RC = &X86::VR128RegClass;
2472       else if (RegVT == MVT::x86mmx)
2473         RC = &X86::VR64RegClass;
2474       else if (RegVT == MVT::i1)
2475         RC = &X86::VK1RegClass;
2476       else if (RegVT == MVT::v8i1)
2477         RC = &X86::VK8RegClass;
2478       else if (RegVT == MVT::v16i1)
2479         RC = &X86::VK16RegClass;
2480       else if (RegVT == MVT::v32i1)
2481         RC = &X86::VK32RegClass;
2482       else if (RegVT == MVT::v64i1)
2483         RC = &X86::VK64RegClass;
2484       else
2485         llvm_unreachable("Unknown argument type!");
2486
2487       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2488       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2489
2490       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2491       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2492       // right size.
2493       if (VA.getLocInfo() == CCValAssign::SExt)
2494         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2495                                DAG.getValueType(VA.getValVT()));
2496       else if (VA.getLocInfo() == CCValAssign::ZExt)
2497         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2498                                DAG.getValueType(VA.getValVT()));
2499       else if (VA.getLocInfo() == CCValAssign::BCvt)
2500         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2501
2502       if (VA.isExtInLoc()) {
2503         // Handle MMX values passed in XMM regs.
2504         if (RegVT.isVector())
2505           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2506         else
2507           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2508       }
2509     } else {
2510       assert(VA.isMemLoc());
2511       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2512     }
2513
2514     // If value is passed via pointer - do a load.
2515     if (VA.getLocInfo() == CCValAssign::Indirect)
2516       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2517                              MachinePointerInfo(), false, false, false, 0);
2518
2519     InVals.push_back(ArgValue);
2520   }
2521
2522   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2523     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2524       // The x86-64 ABIs require that for returning structs by value we copy
2525       // the sret argument into %rax/%eax (depending on ABI) for the return.
2526       // Win32 requires us to put the sret argument to %eax as well.
2527       // Save the argument into a virtual register so that we can access it
2528       // from the return points.
2529       if (Ins[i].Flags.isSRet()) {
2530         unsigned Reg = FuncInfo->getSRetReturnReg();
2531         if (!Reg) {
2532           MVT PtrTy = getPointerTy();
2533           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2534           FuncInfo->setSRetReturnReg(Reg);
2535         }
2536         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2537         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2538         break;
2539       }
2540     }
2541   }
2542
2543   unsigned StackSize = CCInfo.getNextStackOffset();
2544   // Align stack specially for tail calls.
2545   if (FuncIsMadeTailCallSafe(CallConv,
2546                              MF.getTarget().Options.GuaranteedTailCallOpt))
2547     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2548
2549   // If the function takes variable number of arguments, make a frame index for
2550   // the start of the first vararg value... for expansion of llvm.va_start. We
2551   // can skip this if there are no va_start calls.
2552   if (MFI->hasVAStart() &&
2553       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2554                    CallConv != CallingConv::X86_ThisCall))) {
2555     FuncInfo->setVarArgsFrameIndex(
2556         MFI->CreateFixedObject(1, StackSize, true));
2557   }
2558
2559   // Figure out if XMM registers are in use.
2560   assert(!(MF.getTarget().Options.UseSoftFloat &&
2561            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2562          "SSE register cannot be used when SSE is disabled!");
2563
2564   // 64-bit calling conventions support varargs and register parameters, so we
2565   // have to do extra work to spill them in the prologue.
2566   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2567     // Find the first unallocated argument registers.
2568     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2569     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2570     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2571     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2572     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2573            "SSE register cannot be used when SSE is disabled!");
2574
2575     // Gather all the live in physical registers.
2576     SmallVector<SDValue, 6> LiveGPRs;
2577     SmallVector<SDValue, 8> LiveXMMRegs;
2578     SDValue ALVal;
2579     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2580       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2581       LiveGPRs.push_back(
2582           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2583     }
2584     if (!ArgXMMs.empty()) {
2585       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2586       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2587       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2588         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2589         LiveXMMRegs.push_back(
2590             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2591       }
2592     }
2593
2594     if (IsWin64) {
2595       const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2596       // Get to the caller-allocated home save location.  Add 8 to account
2597       // for the return address.
2598       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2599       FuncInfo->setRegSaveFrameIndex(
2600           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2601       // Fixup to set vararg frame on shadow area (4 x i64).
2602       if (NumIntRegs < 4)
2603         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2604     } else {
2605       // For X86-64, if there are vararg parameters that are passed via
2606       // registers, then we must store them to their spots on the stack so
2607       // they may be loaded by deferencing the result of va_next.
2608       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2609       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2610       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2611           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2612     }
2613
2614     // Store the integer parameter registers.
2615     SmallVector<SDValue, 8> MemOps;
2616     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2617                                       getPointerTy());
2618     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2619     for (SDValue Val : LiveGPRs) {
2620       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2621                                 DAG.getIntPtrConstant(Offset));
2622       SDValue Store =
2623         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2624                      MachinePointerInfo::getFixedStack(
2625                        FuncInfo->getRegSaveFrameIndex(), Offset),
2626                      false, false, 0);
2627       MemOps.push_back(Store);
2628       Offset += 8;
2629     }
2630
2631     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2632       // Now store the XMM (fp + vector) parameter registers.
2633       SmallVector<SDValue, 12> SaveXMMOps;
2634       SaveXMMOps.push_back(Chain);
2635       SaveXMMOps.push_back(ALVal);
2636       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2637                              FuncInfo->getRegSaveFrameIndex()));
2638       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2639                              FuncInfo->getVarArgsFPOffset()));
2640       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2641                         LiveXMMRegs.end());
2642       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2643                                    MVT::Other, SaveXMMOps));
2644     }
2645
2646     if (!MemOps.empty())
2647       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2648   }
2649
2650   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2651     // Find the largest legal vector type.
2652     MVT VecVT = MVT::Other;
2653     // FIXME: Only some x86_32 calling conventions support AVX512.
2654     if (Subtarget->hasAVX512() &&
2655         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2656                      CallConv == CallingConv::Intel_OCL_BI)))
2657       VecVT = MVT::v16f32;
2658     else if (Subtarget->hasAVX())
2659       VecVT = MVT::v8f32;
2660     else if (Subtarget->hasSSE2())
2661       VecVT = MVT::v4f32;
2662
2663     // We forward some GPRs and some vector types.
2664     SmallVector<MVT, 2> RegParmTypes;
2665     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2666     RegParmTypes.push_back(IntVT);
2667     if (VecVT != MVT::Other)
2668       RegParmTypes.push_back(VecVT);
2669
2670     // Compute the set of forwarded registers. The rest are scratch.
2671     SmallVectorImpl<ForwardedRegister> &Forwards =
2672         FuncInfo->getForwardedMustTailRegParms();
2673     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2674
2675     // Conservatively forward AL on x86_64, since it might be used for varargs.
2676     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2677       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2678       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2679     }
2680
2681     // Copy all forwards from physical to virtual registers.
2682     for (ForwardedRegister &F : Forwards) {
2683       // FIXME: Can we use a less constrained schedule?
2684       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2685       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2686       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2687     }
2688   }
2689
2690   // Some CCs need callee pop.
2691   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2692                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2693     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2694   } else {
2695     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2696     // If this is an sret function, the return should pop the hidden pointer.
2697     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2698         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2699         argsAreStructReturn(Ins) == StackStructReturn)
2700       FuncInfo->setBytesToPopOnReturn(4);
2701   }
2702
2703   if (!Is64Bit) {
2704     // RegSaveFrameIndex is X86-64 only.
2705     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2706     if (CallConv == CallingConv::X86_FastCall ||
2707         CallConv == CallingConv::X86_ThisCall)
2708       // fastcc functions can't have varargs.
2709       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2710   }
2711
2712   FuncInfo->setArgumentStackSize(StackSize);
2713
2714   return Chain;
2715 }
2716
2717 SDValue
2718 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2719                                     SDValue StackPtr, SDValue Arg,
2720                                     SDLoc dl, SelectionDAG &DAG,
2721                                     const CCValAssign &VA,
2722                                     ISD::ArgFlagsTy Flags) const {
2723   unsigned LocMemOffset = VA.getLocMemOffset();
2724   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2725   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2726   if (Flags.isByVal())
2727     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2728
2729   return DAG.getStore(Chain, dl, Arg, PtrOff,
2730                       MachinePointerInfo::getStack(LocMemOffset),
2731                       false, false, 0);
2732 }
2733
2734 /// Emit a load of return address if tail call
2735 /// optimization is performed and it is required.
2736 SDValue
2737 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2738                                            SDValue &OutRetAddr, SDValue Chain,
2739                                            bool IsTailCall, bool Is64Bit,
2740                                            int FPDiff, SDLoc dl) const {
2741   // Adjust the Return address stack slot.
2742   EVT VT = getPointerTy();
2743   OutRetAddr = getReturnAddressFrameIndex(DAG);
2744
2745   // Load the "old" Return address.
2746   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2747                            false, false, false, 0);
2748   return SDValue(OutRetAddr.getNode(), 1);
2749 }
2750
2751 /// Emit a store of the return address if tail call
2752 /// optimization is performed and it is required (FPDiff!=0).
2753 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2754                                         SDValue Chain, SDValue RetAddrFrIdx,
2755                                         EVT PtrVT, unsigned SlotSize,
2756                                         int FPDiff, SDLoc dl) {
2757   // Store the return address to the appropriate stack slot.
2758   if (!FPDiff) return Chain;
2759   // Calculate the new stack slot for the return address.
2760   int NewReturnAddrFI =
2761     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2762                                          false);
2763   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2764   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2765                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2766                        false, false, 0);
2767   return Chain;
2768 }
2769
2770 SDValue
2771 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2772                              SmallVectorImpl<SDValue> &InVals) const {
2773   SelectionDAG &DAG                     = CLI.DAG;
2774   SDLoc &dl                             = CLI.DL;
2775   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2776   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2777   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2778   SDValue Chain                         = CLI.Chain;
2779   SDValue Callee                        = CLI.Callee;
2780   CallingConv::ID CallConv              = CLI.CallConv;
2781   bool &isTailCall                      = CLI.IsTailCall;
2782   bool isVarArg                         = CLI.IsVarArg;
2783
2784   MachineFunction &MF = DAG.getMachineFunction();
2785   bool Is64Bit        = Subtarget->is64Bit();
2786   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2787   StructReturnType SR = callIsStructReturn(Outs);
2788   bool IsSibcall      = false;
2789   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2790
2791   if (MF.getTarget().Options.DisableTailCalls)
2792     isTailCall = false;
2793
2794   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2795   if (IsMustTail) {
2796     // Force this to be a tail call.  The verifier rules are enough to ensure
2797     // that we can lower this successfully without moving the return address
2798     // around.
2799     isTailCall = true;
2800   } else if (isTailCall) {
2801     // Check if it's really possible to do a tail call.
2802     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2803                     isVarArg, SR != NotStructReturn,
2804                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2805                     Outs, OutVals, Ins, DAG);
2806
2807     // Sibcalls are automatically detected tailcalls which do not require
2808     // ABI changes.
2809     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2810       IsSibcall = true;
2811
2812     if (isTailCall)
2813       ++NumTailCalls;
2814   }
2815
2816   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2817          "Var args not supported with calling convention fastcc, ghc or hipe");
2818
2819   // Analyze operands of the call, assigning locations to each operand.
2820   SmallVector<CCValAssign, 16> ArgLocs;
2821   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2822
2823   // Allocate shadow area for Win64
2824   if (IsWin64)
2825     CCInfo.AllocateStack(32, 8);
2826
2827   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2828
2829   // Get a count of how many bytes are to be pushed on the stack.
2830   unsigned NumBytes = CCInfo.getNextStackOffset();
2831   if (IsSibcall)
2832     // This is a sibcall. The memory operands are available in caller's
2833     // own caller's stack.
2834     NumBytes = 0;
2835   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2836            IsTailCallConvention(CallConv))
2837     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2838
2839   int FPDiff = 0;
2840   if (isTailCall && !IsSibcall && !IsMustTail) {
2841     // Lower arguments at fp - stackoffset + fpdiff.
2842     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2843
2844     FPDiff = NumBytesCallerPushed - NumBytes;
2845
2846     // Set the delta of movement of the returnaddr stackslot.
2847     // But only set if delta is greater than previous delta.
2848     if (FPDiff < X86Info->getTCReturnAddrDelta())
2849       X86Info->setTCReturnAddrDelta(FPDiff);
2850   }
2851
2852   unsigned NumBytesToPush = NumBytes;
2853   unsigned NumBytesToPop = NumBytes;
2854
2855   // If we have an inalloca argument, all stack space has already been allocated
2856   // for us and be right at the top of the stack.  We don't support multiple
2857   // arguments passed in memory when using inalloca.
2858   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2859     NumBytesToPush = 0;
2860     if (!ArgLocs.back().isMemLoc())
2861       report_fatal_error("cannot use inalloca attribute on a register "
2862                          "parameter");
2863     if (ArgLocs.back().getLocMemOffset() != 0)
2864       report_fatal_error("any parameter with the inalloca attribute must be "
2865                          "the only memory argument");
2866   }
2867
2868   if (!IsSibcall)
2869     Chain = DAG.getCALLSEQ_START(
2870         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2871
2872   SDValue RetAddrFrIdx;
2873   // Load return address for tail calls.
2874   if (isTailCall && FPDiff)
2875     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2876                                     Is64Bit, FPDiff, dl);
2877
2878   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2879   SmallVector<SDValue, 8> MemOpChains;
2880   SDValue StackPtr;
2881
2882   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2883   // of tail call optimization arguments are handle later.
2884   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2885   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2886     // Skip inalloca arguments, they have already been written.
2887     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2888     if (Flags.isInAlloca())
2889       continue;
2890
2891     CCValAssign &VA = ArgLocs[i];
2892     EVT RegVT = VA.getLocVT();
2893     SDValue Arg = OutVals[i];
2894     bool isByVal = Flags.isByVal();
2895
2896     // Promote the value if needed.
2897     switch (VA.getLocInfo()) {
2898     default: llvm_unreachable("Unknown loc info!");
2899     case CCValAssign::Full: break;
2900     case CCValAssign::SExt:
2901       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2902       break;
2903     case CCValAssign::ZExt:
2904       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2905       break;
2906     case CCValAssign::AExt:
2907       if (RegVT.is128BitVector()) {
2908         // Special case: passing MMX values in XMM registers.
2909         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2910         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2911         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2912       } else
2913         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2914       break;
2915     case CCValAssign::BCvt:
2916       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2917       break;
2918     case CCValAssign::Indirect: {
2919       // Store the argument.
2920       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2921       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2922       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2923                            MachinePointerInfo::getFixedStack(FI),
2924                            false, false, 0);
2925       Arg = SpillSlot;
2926       break;
2927     }
2928     }
2929
2930     if (VA.isRegLoc()) {
2931       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2932       if (isVarArg && IsWin64) {
2933         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2934         // shadow reg if callee is a varargs function.
2935         unsigned ShadowReg = 0;
2936         switch (VA.getLocReg()) {
2937         case X86::XMM0: ShadowReg = X86::RCX; break;
2938         case X86::XMM1: ShadowReg = X86::RDX; break;
2939         case X86::XMM2: ShadowReg = X86::R8; break;
2940         case X86::XMM3: ShadowReg = X86::R9; break;
2941         }
2942         if (ShadowReg)
2943           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2944       }
2945     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2946       assert(VA.isMemLoc());
2947       if (!StackPtr.getNode())
2948         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2949                                       getPointerTy());
2950       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2951                                              dl, DAG, VA, Flags));
2952     }
2953   }
2954
2955   if (!MemOpChains.empty())
2956     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2957
2958   if (Subtarget->isPICStyleGOT()) {
2959     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2960     // GOT pointer.
2961     if (!isTailCall) {
2962       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2963                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2964     } else {
2965       // If we are tail calling and generating PIC/GOT style code load the
2966       // address of the callee into ECX. The value in ecx is used as target of
2967       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2968       // for tail calls on PIC/GOT architectures. Normally we would just put the
2969       // address of GOT into ebx and then call target@PLT. But for tail calls
2970       // ebx would be restored (since ebx is callee saved) before jumping to the
2971       // target@PLT.
2972
2973       // Note: The actual moving to ECX is done further down.
2974       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2975       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2976           !G->getGlobal()->hasProtectedVisibility())
2977         Callee = LowerGlobalAddress(Callee, DAG);
2978       else if (isa<ExternalSymbolSDNode>(Callee))
2979         Callee = LowerExternalSymbol(Callee, DAG);
2980     }
2981   }
2982
2983   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2984     // From AMD64 ABI document:
2985     // For calls that may call functions that use varargs or stdargs
2986     // (prototype-less calls or calls to functions containing ellipsis (...) in
2987     // the declaration) %al is used as hidden argument to specify the number
2988     // of SSE registers used. The contents of %al do not need to match exactly
2989     // the number of registers, but must be an ubound on the number of SSE
2990     // registers used and is in the range 0 - 8 inclusive.
2991
2992     // Count the number of XMM registers allocated.
2993     static const MCPhysReg XMMArgRegs[] = {
2994       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2995       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2996     };
2997     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2998     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2999            && "SSE registers cannot be used when SSE is disabled");
3000
3001     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3002                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
3003   }
3004
3005   if (isVarArg && IsMustTail) {
3006     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3007     for (const auto &F : Forwards) {
3008       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3009       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3010     }
3011   }
3012
3013   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3014   // don't need this because the eligibility check rejects calls that require
3015   // shuffling arguments passed in memory.
3016   if (!IsSibcall && isTailCall) {
3017     // Force all the incoming stack arguments to be loaded from the stack
3018     // before any new outgoing arguments are stored to the stack, because the
3019     // outgoing stack slots may alias the incoming argument stack slots, and
3020     // the alias isn't otherwise explicit. This is slightly more conservative
3021     // than necessary, because it means that each store effectively depends
3022     // on every argument instead of just those arguments it would clobber.
3023     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3024
3025     SmallVector<SDValue, 8> MemOpChains2;
3026     SDValue FIN;
3027     int FI = 0;
3028     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3029       CCValAssign &VA = ArgLocs[i];
3030       if (VA.isRegLoc())
3031         continue;
3032       assert(VA.isMemLoc());
3033       SDValue Arg = OutVals[i];
3034       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3035       // Skip inalloca arguments.  They don't require any work.
3036       if (Flags.isInAlloca())
3037         continue;
3038       // Create frame index.
3039       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3040       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3041       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3042       FIN = DAG.getFrameIndex(FI, getPointerTy());
3043
3044       if (Flags.isByVal()) {
3045         // Copy relative to framepointer.
3046         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3047         if (!StackPtr.getNode())
3048           StackPtr = DAG.getCopyFromReg(Chain, dl,
3049                                         RegInfo->getStackRegister(),
3050                                         getPointerTy());
3051         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3052
3053         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3054                                                          ArgChain,
3055                                                          Flags, DAG, dl));
3056       } else {
3057         // Store relative to framepointer.
3058         MemOpChains2.push_back(
3059           DAG.getStore(ArgChain, dl, Arg, FIN,
3060                        MachinePointerInfo::getFixedStack(FI),
3061                        false, false, 0));
3062       }
3063     }
3064
3065     if (!MemOpChains2.empty())
3066       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3067
3068     // Store the return address to the appropriate stack slot.
3069     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3070                                      getPointerTy(), RegInfo->getSlotSize(),
3071                                      FPDiff, dl);
3072   }
3073
3074   // Build a sequence of copy-to-reg nodes chained together with token chain
3075   // and flag operands which copy the outgoing args into registers.
3076   SDValue InFlag;
3077   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3078     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3079                              RegsToPass[i].second, InFlag);
3080     InFlag = Chain.getValue(1);
3081   }
3082
3083   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3084     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3085     // In the 64-bit large code model, we have to make all calls
3086     // through a register, since the call instruction's 32-bit
3087     // pc-relative offset may not be large enough to hold the whole
3088     // address.
3089   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3090     // If the callee is a GlobalAddress node (quite common, every direct call
3091     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3092     // it.
3093     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3094
3095     // We should use extra load for direct calls to dllimported functions in
3096     // non-JIT mode.
3097     const GlobalValue *GV = G->getGlobal();
3098     if (!GV->hasDLLImportStorageClass()) {
3099       unsigned char OpFlags = 0;
3100       bool ExtraLoad = false;
3101       unsigned WrapperKind = ISD::DELETED_NODE;
3102
3103       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3104       // external symbols most go through the PLT in PIC mode.  If the symbol
3105       // has hidden or protected visibility, or if it is static or local, then
3106       // we don't need to use the PLT - we can directly call it.
3107       if (Subtarget->isTargetELF() &&
3108           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3109           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3110         OpFlags = X86II::MO_PLT;
3111       } else if (Subtarget->isPICStyleStubAny() &&
3112                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3113                  (!Subtarget->getTargetTriple().isMacOSX() ||
3114                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3115         // PC-relative references to external symbols should go through $stub,
3116         // unless we're building with the leopard linker or later, which
3117         // automatically synthesizes these stubs.
3118         OpFlags = X86II::MO_DARWIN_STUB;
3119       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3120                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3121         // If the function is marked as non-lazy, generate an indirect call
3122         // which loads from the GOT directly. This avoids runtime overhead
3123         // at the cost of eager binding (and one extra byte of encoding).
3124         OpFlags = X86II::MO_GOTPCREL;
3125         WrapperKind = X86ISD::WrapperRIP;
3126         ExtraLoad = true;
3127       }
3128
3129       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3130                                           G->getOffset(), OpFlags);
3131
3132       // Add a wrapper if needed.
3133       if (WrapperKind != ISD::DELETED_NODE)
3134         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3135       // Add extra indirection if needed.
3136       if (ExtraLoad)
3137         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3138                              MachinePointerInfo::getGOT(),
3139                              false, false, false, 0);
3140     }
3141   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3142     unsigned char OpFlags = 0;
3143
3144     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3145     // external symbols should go through the PLT.
3146     if (Subtarget->isTargetELF() &&
3147         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3148       OpFlags = X86II::MO_PLT;
3149     } else if (Subtarget->isPICStyleStubAny() &&
3150                (!Subtarget->getTargetTriple().isMacOSX() ||
3151                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3152       // PC-relative references to external symbols should go through $stub,
3153       // unless we're building with the leopard linker or later, which
3154       // automatically synthesizes these stubs.
3155       OpFlags = X86II::MO_DARWIN_STUB;
3156     }
3157
3158     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3159                                          OpFlags);
3160   } else if (Subtarget->isTarget64BitILP32() &&
3161              Callee->getValueType(0) == MVT::i32) {
3162     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3163     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3164   }
3165
3166   // Returns a chain & a flag for retval copy to use.
3167   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3168   SmallVector<SDValue, 8> Ops;
3169
3170   if (!IsSibcall && isTailCall) {
3171     Chain = DAG.getCALLSEQ_END(Chain,
3172                                DAG.getIntPtrConstant(NumBytesToPop, true),
3173                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3174     InFlag = Chain.getValue(1);
3175   }
3176
3177   Ops.push_back(Chain);
3178   Ops.push_back(Callee);
3179
3180   if (isTailCall)
3181     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3182
3183   // Add argument registers to the end of the list so that they are known live
3184   // into the call.
3185   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3186     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3187                                   RegsToPass[i].second.getValueType()));
3188
3189   // Add a register mask operand representing the call-preserved registers.
3190   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3191   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3192   assert(Mask && "Missing call preserved mask for calling convention");
3193   Ops.push_back(DAG.getRegisterMask(Mask));
3194
3195   if (InFlag.getNode())
3196     Ops.push_back(InFlag);
3197
3198   if (isTailCall) {
3199     // We used to do:
3200     //// If this is the first return lowered for this function, add the regs
3201     //// to the liveout set for the function.
3202     // This isn't right, although it's probably harmless on x86; liveouts
3203     // should be computed from returns not tail calls.  Consider a void
3204     // function making a tail call to a function returning int.
3205     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3206   }
3207
3208   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3209   InFlag = Chain.getValue(1);
3210
3211   // Create the CALLSEQ_END node.
3212   unsigned NumBytesForCalleeToPop;
3213   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3214                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3215     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3216   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3217            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3218            SR == StackStructReturn)
3219     // If this is a call to a struct-return function, the callee
3220     // pops the hidden struct pointer, so we have to push it back.
3221     // This is common for Darwin/X86, Linux & Mingw32 targets.
3222     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3223     NumBytesForCalleeToPop = 4;
3224   else
3225     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3226
3227   // Returns a flag for retval copy to use.
3228   if (!IsSibcall) {
3229     Chain = DAG.getCALLSEQ_END(Chain,
3230                                DAG.getIntPtrConstant(NumBytesToPop, true),
3231                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3232                                                      true),
3233                                InFlag, dl);
3234     InFlag = Chain.getValue(1);
3235   }
3236
3237   // Handle result values, copying them out of physregs into vregs that we
3238   // return.
3239   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3240                          Ins, dl, DAG, InVals);
3241 }
3242
3243 //===----------------------------------------------------------------------===//
3244 //                Fast Calling Convention (tail call) implementation
3245 //===----------------------------------------------------------------------===//
3246
3247 //  Like std call, callee cleans arguments, convention except that ECX is
3248 //  reserved for storing the tail called function address. Only 2 registers are
3249 //  free for argument passing (inreg). Tail call optimization is performed
3250 //  provided:
3251 //                * tailcallopt is enabled
3252 //                * caller/callee are fastcc
3253 //  On X86_64 architecture with GOT-style position independent code only local
3254 //  (within module) calls are supported at the moment.
3255 //  To keep the stack aligned according to platform abi the function
3256 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3257 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3258 //  If a tail called function callee has more arguments than the caller the
3259 //  caller needs to make sure that there is room to move the RETADDR to. This is
3260 //  achieved by reserving an area the size of the argument delta right after the
3261 //  original RETADDR, but before the saved framepointer or the spilled registers
3262 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3263 //  stack layout:
3264 //    arg1
3265 //    arg2
3266 //    RETADDR
3267 //    [ new RETADDR
3268 //      move area ]
3269 //    (possible EBP)
3270 //    ESI
3271 //    EDI
3272 //    local1 ..
3273
3274 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3275 /// for a 16 byte align requirement.
3276 unsigned
3277 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3278                                                SelectionDAG& DAG) const {
3279   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3280   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3281   unsigned StackAlignment = TFI.getStackAlignment();
3282   uint64_t AlignMask = StackAlignment - 1;
3283   int64_t Offset = StackSize;
3284   unsigned SlotSize = RegInfo->getSlotSize();
3285   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3286     // Number smaller than 12 so just add the difference.
3287     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3288   } else {
3289     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3290     Offset = ((~AlignMask) & Offset) + StackAlignment +
3291       (StackAlignment-SlotSize);
3292   }
3293   return Offset;
3294 }
3295
3296 /// MatchingStackOffset - Return true if the given stack call argument is
3297 /// already available in the same position (relatively) of the caller's
3298 /// incoming argument stack.
3299 static
3300 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3301                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3302                          const X86InstrInfo *TII) {
3303   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3304   int FI = INT_MAX;
3305   if (Arg.getOpcode() == ISD::CopyFromReg) {
3306     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3307     if (!TargetRegisterInfo::isVirtualRegister(VR))
3308       return false;
3309     MachineInstr *Def = MRI->getVRegDef(VR);
3310     if (!Def)
3311       return false;
3312     if (!Flags.isByVal()) {
3313       if (!TII->isLoadFromStackSlot(Def, FI))
3314         return false;
3315     } else {
3316       unsigned Opcode = Def->getOpcode();
3317       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3318            Opcode == X86::LEA64_32r) &&
3319           Def->getOperand(1).isFI()) {
3320         FI = Def->getOperand(1).getIndex();
3321         Bytes = Flags.getByValSize();
3322       } else
3323         return false;
3324     }
3325   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3326     if (Flags.isByVal())
3327       // ByVal argument is passed in as a pointer but it's now being
3328       // dereferenced. e.g.
3329       // define @foo(%struct.X* %A) {
3330       //   tail call @bar(%struct.X* byval %A)
3331       // }
3332       return false;
3333     SDValue Ptr = Ld->getBasePtr();
3334     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3335     if (!FINode)
3336       return false;
3337     FI = FINode->getIndex();
3338   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3339     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3340     FI = FINode->getIndex();
3341     Bytes = Flags.getByValSize();
3342   } else
3343     return false;
3344
3345   assert(FI != INT_MAX);
3346   if (!MFI->isFixedObjectIndex(FI))
3347     return false;
3348   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3349 }
3350
3351 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3352 /// for tail call optimization. Targets which want to do tail call
3353 /// optimization should implement this function.
3354 bool
3355 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3356                                                      CallingConv::ID CalleeCC,
3357                                                      bool isVarArg,
3358                                                      bool isCalleeStructRet,
3359                                                      bool isCallerStructRet,
3360                                                      Type *RetTy,
3361                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3362                                     const SmallVectorImpl<SDValue> &OutVals,
3363                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3364                                                      SelectionDAG &DAG) const {
3365   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3366     return false;
3367
3368   // If -tailcallopt is specified, make fastcc functions tail-callable.
3369   const MachineFunction &MF = DAG.getMachineFunction();
3370   const Function *CallerF = MF.getFunction();
3371
3372   // If the function return type is x86_fp80 and the callee return type is not,
3373   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3374   // perform a tailcall optimization here.
3375   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3376     return false;
3377
3378   CallingConv::ID CallerCC = CallerF->getCallingConv();
3379   bool CCMatch = CallerCC == CalleeCC;
3380   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3381   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3382
3383   // Win64 functions have extra shadow space for argument homing. Don't do the
3384   // sibcall if the caller and callee have mismatched expectations for this
3385   // space.
3386   if (IsCalleeWin64 != IsCallerWin64)
3387     return false;
3388
3389   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3390     if (IsTailCallConvention(CalleeCC) && CCMatch)
3391       return true;
3392     return false;
3393   }
3394
3395   // Look for obvious safe cases to perform tail call optimization that do not
3396   // require ABI changes. This is what gcc calls sibcall.
3397
3398   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3399   // emit a special epilogue.
3400   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3401   if (RegInfo->needsStackRealignment(MF))
3402     return false;
3403
3404   // Also avoid sibcall optimization if either caller or callee uses struct
3405   // return semantics.
3406   if (isCalleeStructRet || isCallerStructRet)
3407     return false;
3408
3409   // An stdcall/thiscall caller is expected to clean up its arguments; the
3410   // callee isn't going to do that.
3411   // FIXME: this is more restrictive than needed. We could produce a tailcall
3412   // when the stack adjustment matches. For example, with a thiscall that takes
3413   // only one argument.
3414   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3415                    CallerCC == CallingConv::X86_ThisCall))
3416     return false;
3417
3418   // Do not sibcall optimize vararg calls unless all arguments are passed via
3419   // registers.
3420   if (isVarArg && !Outs.empty()) {
3421
3422     // Optimizing for varargs on Win64 is unlikely to be safe without
3423     // additional testing.
3424     if (IsCalleeWin64 || IsCallerWin64)
3425       return false;
3426
3427     SmallVector<CCValAssign, 16> ArgLocs;
3428     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3429                    *DAG.getContext());
3430
3431     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3432     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3433       if (!ArgLocs[i].isRegLoc())
3434         return false;
3435   }
3436
3437   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3438   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3439   // this into a sibcall.
3440   bool Unused = false;
3441   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3442     if (!Ins[i].Used) {
3443       Unused = true;
3444       break;
3445     }
3446   }
3447   if (Unused) {
3448     SmallVector<CCValAssign, 16> RVLocs;
3449     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3450                    *DAG.getContext());
3451     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3452     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3453       CCValAssign &VA = RVLocs[i];
3454       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3455         return false;
3456     }
3457   }
3458
3459   // If the calling conventions do not match, then we'd better make sure the
3460   // results are returned in the same way as what the caller expects.
3461   if (!CCMatch) {
3462     SmallVector<CCValAssign, 16> RVLocs1;
3463     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3464                     *DAG.getContext());
3465     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3466
3467     SmallVector<CCValAssign, 16> RVLocs2;
3468     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3469                     *DAG.getContext());
3470     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3471
3472     if (RVLocs1.size() != RVLocs2.size())
3473       return false;
3474     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3475       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3476         return false;
3477       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3478         return false;
3479       if (RVLocs1[i].isRegLoc()) {
3480         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3481           return false;
3482       } else {
3483         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3484           return false;
3485       }
3486     }
3487   }
3488
3489   // If the callee takes no arguments then go on to check the results of the
3490   // call.
3491   if (!Outs.empty()) {
3492     // Check if stack adjustment is needed. For now, do not do this if any
3493     // argument is passed on the stack.
3494     SmallVector<CCValAssign, 16> ArgLocs;
3495     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3496                    *DAG.getContext());
3497
3498     // Allocate shadow area for Win64
3499     if (IsCalleeWin64)
3500       CCInfo.AllocateStack(32, 8);
3501
3502     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3503     if (CCInfo.getNextStackOffset()) {
3504       MachineFunction &MF = DAG.getMachineFunction();
3505       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3506         return false;
3507
3508       // Check if the arguments are already laid out in the right way as
3509       // the caller's fixed stack objects.
3510       MachineFrameInfo *MFI = MF.getFrameInfo();
3511       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3512       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3513       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3514         CCValAssign &VA = ArgLocs[i];
3515         SDValue Arg = OutVals[i];
3516         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3517         if (VA.getLocInfo() == CCValAssign::Indirect)
3518           return false;
3519         if (!VA.isRegLoc()) {
3520           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3521                                    MFI, MRI, TII))
3522             return false;
3523         }
3524       }
3525     }
3526
3527     // If the tailcall address may be in a register, then make sure it's
3528     // possible to register allocate for it. In 32-bit, the call address can
3529     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3530     // callee-saved registers are restored. These happen to be the same
3531     // registers used to pass 'inreg' arguments so watch out for those.
3532     if (!Subtarget->is64Bit() &&
3533         ((!isa<GlobalAddressSDNode>(Callee) &&
3534           !isa<ExternalSymbolSDNode>(Callee)) ||
3535          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3536       unsigned NumInRegs = 0;
3537       // In PIC we need an extra register to formulate the address computation
3538       // for the callee.
3539       unsigned MaxInRegs =
3540         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3541
3542       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3543         CCValAssign &VA = ArgLocs[i];
3544         if (!VA.isRegLoc())
3545           continue;
3546         unsigned Reg = VA.getLocReg();
3547         switch (Reg) {
3548         default: break;
3549         case X86::EAX: case X86::EDX: case X86::ECX:
3550           if (++NumInRegs == MaxInRegs)
3551             return false;
3552           break;
3553         }
3554       }
3555     }
3556   }
3557
3558   return true;
3559 }
3560
3561 FastISel *
3562 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3563                                   const TargetLibraryInfo *libInfo) const {
3564   return X86::createFastISel(funcInfo, libInfo);
3565 }
3566
3567 //===----------------------------------------------------------------------===//
3568 //                           Other Lowering Hooks
3569 //===----------------------------------------------------------------------===//
3570
3571 static bool MayFoldLoad(SDValue Op) {
3572   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3573 }
3574
3575 static bool MayFoldIntoStore(SDValue Op) {
3576   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3577 }
3578
3579 static bool isTargetShuffle(unsigned Opcode) {
3580   switch(Opcode) {
3581   default: return false;
3582   case X86ISD::BLENDI:
3583   case X86ISD::PSHUFB:
3584   case X86ISD::PSHUFD:
3585   case X86ISD::PSHUFHW:
3586   case X86ISD::PSHUFLW:
3587   case X86ISD::SHUFP:
3588   case X86ISD::PALIGNR:
3589   case X86ISD::MOVLHPS:
3590   case X86ISD::MOVLHPD:
3591   case X86ISD::MOVHLPS:
3592   case X86ISD::MOVLPS:
3593   case X86ISD::MOVLPD:
3594   case X86ISD::MOVSHDUP:
3595   case X86ISD::MOVSLDUP:
3596   case X86ISD::MOVDDUP:
3597   case X86ISD::MOVSS:
3598   case X86ISD::MOVSD:
3599   case X86ISD::UNPCKL:
3600   case X86ISD::UNPCKH:
3601   case X86ISD::VPERMILPI:
3602   case X86ISD::VPERM2X128:
3603   case X86ISD::VPERMI:
3604     return true;
3605   }
3606 }
3607
3608 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3609                                     SDValue V1, unsigned TargetMask,
3610                                     SelectionDAG &DAG) {
3611   switch(Opc) {
3612   default: llvm_unreachable("Unknown x86 shuffle node");
3613   case X86ISD::PSHUFD:
3614   case X86ISD::PSHUFHW:
3615   case X86ISD::PSHUFLW:
3616   case X86ISD::VPERMILPI:
3617   case X86ISD::VPERMI:
3618     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3619   }
3620 }
3621
3622 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3623                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3624   switch(Opc) {
3625   default: llvm_unreachable("Unknown x86 shuffle node");
3626   case X86ISD::MOVLHPS:
3627   case X86ISD::MOVLHPD:
3628   case X86ISD::MOVHLPS:
3629   case X86ISD::MOVLPS:
3630   case X86ISD::MOVLPD:
3631   case X86ISD::MOVSS:
3632   case X86ISD::MOVSD:
3633   case X86ISD::UNPCKL:
3634   case X86ISD::UNPCKH:
3635     return DAG.getNode(Opc, dl, VT, V1, V2);
3636   }
3637 }
3638
3639 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3640   MachineFunction &MF = DAG.getMachineFunction();
3641   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3642   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3643   int ReturnAddrIndex = FuncInfo->getRAIndex();
3644
3645   if (ReturnAddrIndex == 0) {
3646     // Set up a frame object for the return address.
3647     unsigned SlotSize = RegInfo->getSlotSize();
3648     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3649                                                            -(int64_t)SlotSize,
3650                                                            false);
3651     FuncInfo->setRAIndex(ReturnAddrIndex);
3652   }
3653
3654   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3655 }
3656
3657 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3658                                        bool hasSymbolicDisplacement) {
3659   // Offset should fit into 32 bit immediate field.
3660   if (!isInt<32>(Offset))
3661     return false;
3662
3663   // If we don't have a symbolic displacement - we don't have any extra
3664   // restrictions.
3665   if (!hasSymbolicDisplacement)
3666     return true;
3667
3668   // FIXME: Some tweaks might be needed for medium code model.
3669   if (M != CodeModel::Small && M != CodeModel::Kernel)
3670     return false;
3671
3672   // For small code model we assume that latest object is 16MB before end of 31
3673   // bits boundary. We may also accept pretty large negative constants knowing
3674   // that all objects are in the positive half of address space.
3675   if (M == CodeModel::Small && Offset < 16*1024*1024)
3676     return true;
3677
3678   // For kernel code model we know that all object resist in the negative half
3679   // of 32bits address space. We may not accept negative offsets, since they may
3680   // be just off and we may accept pretty large positive ones.
3681   if (M == CodeModel::Kernel && Offset >= 0)
3682     return true;
3683
3684   return false;
3685 }
3686
3687 /// isCalleePop - Determines whether the callee is required to pop its
3688 /// own arguments. Callee pop is necessary to support tail calls.
3689 bool X86::isCalleePop(CallingConv::ID CallingConv,
3690                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3691   switch (CallingConv) {
3692   default:
3693     return false;
3694   case CallingConv::X86_StdCall:
3695   case CallingConv::X86_FastCall:
3696   case CallingConv::X86_ThisCall:
3697     return !is64Bit;
3698   case CallingConv::Fast:
3699   case CallingConv::GHC:
3700   case CallingConv::HiPE:
3701     if (IsVarArg)
3702       return false;
3703     return TailCallOpt;
3704   }
3705 }
3706
3707 /// \brief Return true if the condition is an unsigned comparison operation.
3708 static bool isX86CCUnsigned(unsigned X86CC) {
3709   switch (X86CC) {
3710   default: llvm_unreachable("Invalid integer condition!");
3711   case X86::COND_E:     return true;
3712   case X86::COND_G:     return false;
3713   case X86::COND_GE:    return false;
3714   case X86::COND_L:     return false;
3715   case X86::COND_LE:    return false;
3716   case X86::COND_NE:    return true;
3717   case X86::COND_B:     return true;
3718   case X86::COND_A:     return true;
3719   case X86::COND_BE:    return true;
3720   case X86::COND_AE:    return true;
3721   }
3722   llvm_unreachable("covered switch fell through?!");
3723 }
3724
3725 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3726 /// specific condition code, returning the condition code and the LHS/RHS of the
3727 /// comparison to make.
3728 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3729                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3730   if (!isFP) {
3731     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3732       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3733         // X > -1   -> X == 0, jump !sign.
3734         RHS = DAG.getConstant(0, RHS.getValueType());
3735         return X86::COND_NS;
3736       }
3737       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3738         // X < 0   -> X == 0, jump on sign.
3739         return X86::COND_S;
3740       }
3741       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3742         // X < 1   -> X <= 0
3743         RHS = DAG.getConstant(0, RHS.getValueType());
3744         return X86::COND_LE;
3745       }
3746     }
3747
3748     switch (SetCCOpcode) {
3749     default: llvm_unreachable("Invalid integer condition!");
3750     case ISD::SETEQ:  return X86::COND_E;
3751     case ISD::SETGT:  return X86::COND_G;
3752     case ISD::SETGE:  return X86::COND_GE;
3753     case ISD::SETLT:  return X86::COND_L;
3754     case ISD::SETLE:  return X86::COND_LE;
3755     case ISD::SETNE:  return X86::COND_NE;
3756     case ISD::SETULT: return X86::COND_B;
3757     case ISD::SETUGT: return X86::COND_A;
3758     case ISD::SETULE: return X86::COND_BE;
3759     case ISD::SETUGE: return X86::COND_AE;
3760     }
3761   }
3762
3763   // First determine if it is required or is profitable to flip the operands.
3764
3765   // If LHS is a foldable load, but RHS is not, flip the condition.
3766   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3767       !ISD::isNON_EXTLoad(RHS.getNode())) {
3768     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3769     std::swap(LHS, RHS);
3770   }
3771
3772   switch (SetCCOpcode) {
3773   default: break;
3774   case ISD::SETOLT:
3775   case ISD::SETOLE:
3776   case ISD::SETUGT:
3777   case ISD::SETUGE:
3778     std::swap(LHS, RHS);
3779     break;
3780   }
3781
3782   // On a floating point condition, the flags are set as follows:
3783   // ZF  PF  CF   op
3784   //  0 | 0 | 0 | X > Y
3785   //  0 | 0 | 1 | X < Y
3786   //  1 | 0 | 0 | X == Y
3787   //  1 | 1 | 1 | unordered
3788   switch (SetCCOpcode) {
3789   default: llvm_unreachable("Condcode should be pre-legalized away");
3790   case ISD::SETUEQ:
3791   case ISD::SETEQ:   return X86::COND_E;
3792   case ISD::SETOLT:              // flipped
3793   case ISD::SETOGT:
3794   case ISD::SETGT:   return X86::COND_A;
3795   case ISD::SETOLE:              // flipped
3796   case ISD::SETOGE:
3797   case ISD::SETGE:   return X86::COND_AE;
3798   case ISD::SETUGT:              // flipped
3799   case ISD::SETULT:
3800   case ISD::SETLT:   return X86::COND_B;
3801   case ISD::SETUGE:              // flipped
3802   case ISD::SETULE:
3803   case ISD::SETLE:   return X86::COND_BE;
3804   case ISD::SETONE:
3805   case ISD::SETNE:   return X86::COND_NE;
3806   case ISD::SETUO:   return X86::COND_P;
3807   case ISD::SETO:    return X86::COND_NP;
3808   case ISD::SETOEQ:
3809   case ISD::SETUNE:  return X86::COND_INVALID;
3810   }
3811 }
3812
3813 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3814 /// code. Current x86 isa includes the following FP cmov instructions:
3815 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3816 static bool hasFPCMov(unsigned X86CC) {
3817   switch (X86CC) {
3818   default:
3819     return false;
3820   case X86::COND_B:
3821   case X86::COND_BE:
3822   case X86::COND_E:
3823   case X86::COND_P:
3824   case X86::COND_A:
3825   case X86::COND_AE:
3826   case X86::COND_NE:
3827   case X86::COND_NP:
3828     return true;
3829   }
3830 }
3831
3832 /// isFPImmLegal - Returns true if the target can instruction select the
3833 /// specified FP immediate natively. If false, the legalizer will
3834 /// materialize the FP immediate as a load from a constant pool.
3835 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3836   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3837     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3838       return true;
3839   }
3840   return false;
3841 }
3842
3843 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3844                                               ISD::LoadExtType ExtTy,
3845                                               EVT NewVT) const {
3846   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3847   // relocation target a movq or addq instruction: don't let the load shrink.
3848   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3849   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3850     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3851       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3852   return true;
3853 }
3854
3855 /// \brief Returns true if it is beneficial to convert a load of a constant
3856 /// to just the constant itself.
3857 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3858                                                           Type *Ty) const {
3859   assert(Ty->isIntegerTy());
3860
3861   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3862   if (BitSize == 0 || BitSize > 64)
3863     return false;
3864   return true;
3865 }
3866
3867 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3868                                                 unsigned Index) const {
3869   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3870     return false;
3871
3872   return (Index == 0 || Index == ResVT.getVectorNumElements());
3873 }
3874
3875 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3876   // Speculate cttz only if we can directly use TZCNT.
3877   return Subtarget->hasBMI();
3878 }
3879
3880 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3881   // Speculate ctlz only if we can directly use LZCNT.
3882   return Subtarget->hasLZCNT();
3883 }
3884
3885 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3886 /// the specified range (L, H].
3887 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3888   return (Val < 0) || (Val >= Low && Val < Hi);
3889 }
3890
3891 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3892 /// specified value.
3893 static bool isUndefOrEqual(int Val, int CmpVal) {
3894   return (Val < 0 || Val == CmpVal);
3895 }
3896
3897 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3898 /// from position Pos and ending in Pos+Size, falls within the specified
3899 /// sequential range (Low, Low+Size]. or is undef.
3900 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3901                                        unsigned Pos, unsigned Size, int Low) {
3902   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3903     if (!isUndefOrEqual(Mask[i], Low))
3904       return false;
3905   return true;
3906 }
3907
3908 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3909 /// the two vector operands have swapped position.
3910 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3911                                      unsigned NumElems) {
3912   for (unsigned i = 0; i != NumElems; ++i) {
3913     int idx = Mask[i];
3914     if (idx < 0)
3915       continue;
3916     else if (idx < (int)NumElems)
3917       Mask[i] = idx + NumElems;
3918     else
3919       Mask[i] = idx - NumElems;
3920   }
3921 }
3922
3923 /// isVEXTRACTIndex - Return true if the specified
3924 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3925 /// suitable for instruction that extract 128 or 256 bit vectors
3926 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3927   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3928   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3929     return false;
3930
3931   // The index should be aligned on a vecWidth-bit boundary.
3932   uint64_t Index =
3933     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3934
3935   MVT VT = N->getSimpleValueType(0);
3936   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3937   bool Result = (Index * ElSize) % vecWidth == 0;
3938
3939   return Result;
3940 }
3941
3942 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3943 /// operand specifies a subvector insert that is suitable for input to
3944 /// insertion of 128 or 256-bit subvectors
3945 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3946   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3947   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3948     return false;
3949   // The index should be aligned on a vecWidth-bit boundary.
3950   uint64_t Index =
3951     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3952
3953   MVT VT = N->getSimpleValueType(0);
3954   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3955   bool Result = (Index * ElSize) % vecWidth == 0;
3956
3957   return Result;
3958 }
3959
3960 bool X86::isVINSERT128Index(SDNode *N) {
3961   return isVINSERTIndex(N, 128);
3962 }
3963
3964 bool X86::isVINSERT256Index(SDNode *N) {
3965   return isVINSERTIndex(N, 256);
3966 }
3967
3968 bool X86::isVEXTRACT128Index(SDNode *N) {
3969   return isVEXTRACTIndex(N, 128);
3970 }
3971
3972 bool X86::isVEXTRACT256Index(SDNode *N) {
3973   return isVEXTRACTIndex(N, 256);
3974 }
3975
3976 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3977   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3978   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3979     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3980
3981   uint64_t Index =
3982     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3983
3984   MVT VecVT = N->getOperand(0).getSimpleValueType();
3985   MVT ElVT = VecVT.getVectorElementType();
3986
3987   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3988   return Index / NumElemsPerChunk;
3989 }
3990
3991 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3992   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3993   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3994     llvm_unreachable("Illegal insert subvector for VINSERT");
3995
3996   uint64_t Index =
3997     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3998
3999   MVT VecVT = N->getSimpleValueType(0);
4000   MVT ElVT = VecVT.getVectorElementType();
4001
4002   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4003   return Index / NumElemsPerChunk;
4004 }
4005
4006 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4007 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4008 /// and VINSERTI128 instructions.
4009 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4010   return getExtractVEXTRACTImmediate(N, 128);
4011 }
4012
4013 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4014 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4015 /// and VINSERTI64x4 instructions.
4016 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4017   return getExtractVEXTRACTImmediate(N, 256);
4018 }
4019
4020 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4021 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4022 /// and VINSERTI128 instructions.
4023 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4024   return getInsertVINSERTImmediate(N, 128);
4025 }
4026
4027 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4028 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4029 /// and VINSERTI64x4 instructions.
4030 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4031   return getInsertVINSERTImmediate(N, 256);
4032 }
4033
4034 /// isZero - Returns true if Elt is a constant integer zero
4035 static bool isZero(SDValue V) {
4036   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4037   return C && C->isNullValue();
4038 }
4039
4040 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4041 /// constant +0.0.
4042 bool X86::isZeroNode(SDValue Elt) {
4043   if (isZero(Elt))
4044     return true;
4045   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4046     return CFP->getValueAPF().isPosZero();
4047   return false;
4048 }
4049
4050 /// getZeroVector - Returns a vector of specified type with all zero elements.
4051 ///
4052 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4053                              SelectionDAG &DAG, SDLoc dl) {
4054   assert(VT.isVector() && "Expected a vector type");
4055
4056   // Always build SSE zero vectors as <4 x i32> bitcasted
4057   // to their dest type. This ensures they get CSE'd.
4058   SDValue Vec;
4059   if (VT.is128BitVector()) {  // SSE
4060     if (Subtarget->hasSSE2()) {  // SSE2
4061       SDValue Cst = DAG.getConstant(0, MVT::i32);
4062       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4063     } else { // SSE1
4064       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4065       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4066     }
4067   } else if (VT.is256BitVector()) { // AVX
4068     if (Subtarget->hasInt256()) { // AVX2
4069       SDValue Cst = DAG.getConstant(0, MVT::i32);
4070       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4071       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4072     } else {
4073       // 256-bit logic and arithmetic instructions in AVX are all
4074       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4075       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4076       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4077       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4078     }
4079   } else if (VT.is512BitVector()) { // AVX-512
4080       SDValue Cst = DAG.getConstant(0, MVT::i32);
4081       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4082                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4083       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4084   } else if (VT.getScalarType() == MVT::i1) {
4085     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4086     SDValue Cst = DAG.getConstant(0, MVT::i1);
4087     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4088     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4089   } else
4090     llvm_unreachable("Unexpected vector type");
4091
4092   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4093 }
4094
4095 /// getOnesVector - Returns a vector of specified type with all bits set.
4096 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4097 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4098 /// Then bitcast to their original type, ensuring they get CSE'd.
4099 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4100                              SDLoc dl) {
4101   assert(VT.isVector() && "Expected a vector type");
4102
4103   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4104   SDValue Vec;
4105   if (VT.is256BitVector()) {
4106     if (HasInt256) { // AVX2
4107       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4108       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4109     } else { // AVX
4110       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4111       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4112     }
4113   } else if (VT.is128BitVector()) {
4114     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4115   } else
4116     llvm_unreachable("Unexpected vector type");
4117
4118   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4119 }
4120
4121 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4122 /// operation of specified width.
4123 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4124                        SDValue V2) {
4125   unsigned NumElems = VT.getVectorNumElements();
4126   SmallVector<int, 8> Mask;
4127   Mask.push_back(NumElems);
4128   for (unsigned i = 1; i != NumElems; ++i)
4129     Mask.push_back(i);
4130   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4131 }
4132
4133 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4134 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4135                           SDValue V2) {
4136   unsigned NumElems = VT.getVectorNumElements();
4137   SmallVector<int, 8> Mask;
4138   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4139     Mask.push_back(i);
4140     Mask.push_back(i + NumElems);
4141   }
4142   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4143 }
4144
4145 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4146 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4147                           SDValue V2) {
4148   unsigned NumElems = VT.getVectorNumElements();
4149   SmallVector<int, 8> Mask;
4150   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4151     Mask.push_back(i + Half);
4152     Mask.push_back(i + NumElems + Half);
4153   }
4154   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4155 }
4156
4157 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4158 /// vector of zero or undef vector.  This produces a shuffle where the low
4159 /// element of V2 is swizzled into the zero/undef vector, landing at element
4160 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4161 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4162                                            bool IsZero,
4163                                            const X86Subtarget *Subtarget,
4164                                            SelectionDAG &DAG) {
4165   MVT VT = V2.getSimpleValueType();
4166   SDValue V1 = IsZero
4167     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4168   unsigned NumElems = VT.getVectorNumElements();
4169   SmallVector<int, 16> MaskVec;
4170   for (unsigned i = 0; i != NumElems; ++i)
4171     // If this is the insertion idx, put the low elt of V2 here.
4172     MaskVec.push_back(i == Idx ? NumElems : i);
4173   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4174 }
4175
4176 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4177 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4178 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4179 /// shuffles which use a single input multiple times, and in those cases it will
4180 /// adjust the mask to only have indices within that single input.
4181 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4182                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4183   unsigned NumElems = VT.getVectorNumElements();
4184   SDValue ImmN;
4185
4186   IsUnary = false;
4187   bool IsFakeUnary = false;
4188   switch(N->getOpcode()) {
4189   case X86ISD::BLENDI:
4190     ImmN = N->getOperand(N->getNumOperands()-1);
4191     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4192     break;
4193   case X86ISD::SHUFP:
4194     ImmN = N->getOperand(N->getNumOperands()-1);
4195     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4196     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4197     break;
4198   case X86ISD::UNPCKH:
4199     DecodeUNPCKHMask(VT, Mask);
4200     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4201     break;
4202   case X86ISD::UNPCKL:
4203     DecodeUNPCKLMask(VT, Mask);
4204     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4205     break;
4206   case X86ISD::MOVHLPS:
4207     DecodeMOVHLPSMask(NumElems, Mask);
4208     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4209     break;
4210   case X86ISD::MOVLHPS:
4211     DecodeMOVLHPSMask(NumElems, Mask);
4212     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4213     break;
4214   case X86ISD::PALIGNR:
4215     ImmN = N->getOperand(N->getNumOperands()-1);
4216     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4217     break;
4218   case X86ISD::PSHUFD:
4219   case X86ISD::VPERMILPI:
4220     ImmN = N->getOperand(N->getNumOperands()-1);
4221     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4222     IsUnary = true;
4223     break;
4224   case X86ISD::PSHUFHW:
4225     ImmN = N->getOperand(N->getNumOperands()-1);
4226     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4227     IsUnary = true;
4228     break;
4229   case X86ISD::PSHUFLW:
4230     ImmN = N->getOperand(N->getNumOperands()-1);
4231     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4232     IsUnary = true;
4233     break;
4234   case X86ISD::PSHUFB: {
4235     IsUnary = true;
4236     SDValue MaskNode = N->getOperand(1);
4237     while (MaskNode->getOpcode() == ISD::BITCAST)
4238       MaskNode = MaskNode->getOperand(0);
4239
4240     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4241       // If we have a build-vector, then things are easy.
4242       EVT VT = MaskNode.getValueType();
4243       assert(VT.isVector() &&
4244              "Can't produce a non-vector with a build_vector!");
4245       if (!VT.isInteger())
4246         return false;
4247
4248       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4249
4250       SmallVector<uint64_t, 32> RawMask;
4251       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4252         SDValue Op = MaskNode->getOperand(i);
4253         if (Op->getOpcode() == ISD::UNDEF) {
4254           RawMask.push_back((uint64_t)SM_SentinelUndef);
4255           continue;
4256         }
4257         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4258         if (!CN)
4259           return false;
4260         APInt MaskElement = CN->getAPIntValue();
4261
4262         // We now have to decode the element which could be any integer size and
4263         // extract each byte of it.
4264         for (int j = 0; j < NumBytesPerElement; ++j) {
4265           // Note that this is x86 and so always little endian: the low byte is
4266           // the first byte of the mask.
4267           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4268           MaskElement = MaskElement.lshr(8);
4269         }
4270       }
4271       DecodePSHUFBMask(RawMask, Mask);
4272       break;
4273     }
4274
4275     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4276     if (!MaskLoad)
4277       return false;
4278
4279     SDValue Ptr = MaskLoad->getBasePtr();
4280     if (Ptr->getOpcode() == X86ISD::Wrapper)
4281       Ptr = Ptr->getOperand(0);
4282
4283     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4284     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4285       return false;
4286
4287     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4288       DecodePSHUFBMask(C, Mask);
4289       if (Mask.empty())
4290         return false;
4291       break;
4292     }
4293
4294     return false;
4295   }
4296   case X86ISD::VPERMI:
4297     ImmN = N->getOperand(N->getNumOperands()-1);
4298     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4299     IsUnary = true;
4300     break;
4301   case X86ISD::MOVSS:
4302   case X86ISD::MOVSD:
4303     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4304     break;
4305   case X86ISD::VPERM2X128:
4306     ImmN = N->getOperand(N->getNumOperands()-1);
4307     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308     if (Mask.empty()) return false;
4309     break;
4310   case X86ISD::MOVSLDUP:
4311     DecodeMOVSLDUPMask(VT, Mask);
4312     IsUnary = true;
4313     break;
4314   case X86ISD::MOVSHDUP:
4315     DecodeMOVSHDUPMask(VT, Mask);
4316     IsUnary = true;
4317     break;
4318   case X86ISD::MOVDDUP:
4319     DecodeMOVDDUPMask(VT, Mask);
4320     IsUnary = true;
4321     break;
4322   case X86ISD::MOVLHPD:
4323   case X86ISD::MOVLPD:
4324   case X86ISD::MOVLPS:
4325     // Not yet implemented
4326     return false;
4327   default: llvm_unreachable("unknown target shuffle node");
4328   }
4329
4330   // If we have a fake unary shuffle, the shuffle mask is spread across two
4331   // inputs that are actually the same node. Re-map the mask to always point
4332   // into the first input.
4333   if (IsFakeUnary)
4334     for (int &M : Mask)
4335       if (M >= (int)Mask.size())
4336         M -= Mask.size();
4337
4338   return true;
4339 }
4340
4341 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4342 /// element of the result of the vector shuffle.
4343 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4344                                    unsigned Depth) {
4345   if (Depth == 6)
4346     return SDValue();  // Limit search depth.
4347
4348   SDValue V = SDValue(N, 0);
4349   EVT VT = V.getValueType();
4350   unsigned Opcode = V.getOpcode();
4351
4352   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4353   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4354     int Elt = SV->getMaskElt(Index);
4355
4356     if (Elt < 0)
4357       return DAG.getUNDEF(VT.getVectorElementType());
4358
4359     unsigned NumElems = VT.getVectorNumElements();
4360     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4361                                          : SV->getOperand(1);
4362     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4363   }
4364
4365   // Recurse into target specific vector shuffles to find scalars.
4366   if (isTargetShuffle(Opcode)) {
4367     MVT ShufVT = V.getSimpleValueType();
4368     unsigned NumElems = ShufVT.getVectorNumElements();
4369     SmallVector<int, 16> ShuffleMask;
4370     bool IsUnary;
4371
4372     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4373       return SDValue();
4374
4375     int Elt = ShuffleMask[Index];
4376     if (Elt < 0)
4377       return DAG.getUNDEF(ShufVT.getVectorElementType());
4378
4379     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4380                                          : N->getOperand(1);
4381     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4382                                Depth+1);
4383   }
4384
4385   // Actual nodes that may contain scalar elements
4386   if (Opcode == ISD::BITCAST) {
4387     V = V.getOperand(0);
4388     EVT SrcVT = V.getValueType();
4389     unsigned NumElems = VT.getVectorNumElements();
4390
4391     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4392       return SDValue();
4393   }
4394
4395   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4396     return (Index == 0) ? V.getOperand(0)
4397                         : DAG.getUNDEF(VT.getVectorElementType());
4398
4399   if (V.getOpcode() == ISD::BUILD_VECTOR)
4400     return V.getOperand(Index);
4401
4402   return SDValue();
4403 }
4404
4405 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4406 ///
4407 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4408                                        unsigned NumNonZero, unsigned NumZero,
4409                                        SelectionDAG &DAG,
4410                                        const X86Subtarget* Subtarget,
4411                                        const TargetLowering &TLI) {
4412   if (NumNonZero > 8)
4413     return SDValue();
4414
4415   SDLoc dl(Op);
4416   SDValue V;
4417   bool First = true;
4418   for (unsigned i = 0; i < 16; ++i) {
4419     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4420     if (ThisIsNonZero && First) {
4421       if (NumZero)
4422         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4423       else
4424         V = DAG.getUNDEF(MVT::v8i16);
4425       First = false;
4426     }
4427
4428     if ((i & 1) != 0) {
4429       SDValue ThisElt, LastElt;
4430       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4431       if (LastIsNonZero) {
4432         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4433                               MVT::i16, Op.getOperand(i-1));
4434       }
4435       if (ThisIsNonZero) {
4436         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4437         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4438                               ThisElt, DAG.getConstant(8, MVT::i8));
4439         if (LastIsNonZero)
4440           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4441       } else
4442         ThisElt = LastElt;
4443
4444       if (ThisElt.getNode())
4445         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4446                         DAG.getIntPtrConstant(i/2));
4447     }
4448   }
4449
4450   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4451 }
4452
4453 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4454 ///
4455 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4456                                      unsigned NumNonZero, unsigned NumZero,
4457                                      SelectionDAG &DAG,
4458                                      const X86Subtarget* Subtarget,
4459                                      const TargetLowering &TLI) {
4460   if (NumNonZero > 4)
4461     return SDValue();
4462
4463   SDLoc dl(Op);
4464   SDValue V;
4465   bool First = true;
4466   for (unsigned i = 0; i < 8; ++i) {
4467     bool isNonZero = (NonZeros & (1 << i)) != 0;
4468     if (isNonZero) {
4469       if (First) {
4470         if (NumZero)
4471           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4472         else
4473           V = DAG.getUNDEF(MVT::v8i16);
4474         First = false;
4475       }
4476       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4477                       MVT::v8i16, V, Op.getOperand(i),
4478                       DAG.getIntPtrConstant(i));
4479     }
4480   }
4481
4482   return V;
4483 }
4484
4485 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4486 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4487                                      const X86Subtarget *Subtarget,
4488                                      const TargetLowering &TLI) {
4489   // Find all zeroable elements.
4490   std::bitset<4> Zeroable;
4491   for (int i=0; i < 4; ++i) {
4492     SDValue Elt = Op->getOperand(i);
4493     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4494   }
4495   assert(Zeroable.size() - Zeroable.count() > 1 &&
4496          "We expect at least two non-zero elements!");
4497
4498   // We only know how to deal with build_vector nodes where elements are either
4499   // zeroable or extract_vector_elt with constant index.
4500   SDValue FirstNonZero;
4501   unsigned FirstNonZeroIdx;
4502   for (unsigned i=0; i < 4; ++i) {
4503     if (Zeroable[i])
4504       continue;
4505     SDValue Elt = Op->getOperand(i);
4506     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4507         !isa<ConstantSDNode>(Elt.getOperand(1)))
4508       return SDValue();
4509     // Make sure that this node is extracting from a 128-bit vector.
4510     MVT VT = Elt.getOperand(0).getSimpleValueType();
4511     if (!VT.is128BitVector())
4512       return SDValue();
4513     if (!FirstNonZero.getNode()) {
4514       FirstNonZero = Elt;
4515       FirstNonZeroIdx = i;
4516     }
4517   }
4518
4519   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4520   SDValue V1 = FirstNonZero.getOperand(0);
4521   MVT VT = V1.getSimpleValueType();
4522
4523   // See if this build_vector can be lowered as a blend with zero.
4524   SDValue Elt;
4525   unsigned EltMaskIdx, EltIdx;
4526   int Mask[4];
4527   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4528     if (Zeroable[EltIdx]) {
4529       // The zero vector will be on the right hand side.
4530       Mask[EltIdx] = EltIdx+4;
4531       continue;
4532     }
4533
4534     Elt = Op->getOperand(EltIdx);
4535     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4536     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4537     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4538       break;
4539     Mask[EltIdx] = EltIdx;
4540   }
4541
4542   if (EltIdx == 4) {
4543     // Let the shuffle legalizer deal with blend operations.
4544     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4545     if (V1.getSimpleValueType() != VT)
4546       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4547     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4548   }
4549
4550   // See if we can lower this build_vector to a INSERTPS.
4551   if (!Subtarget->hasSSE41())
4552     return SDValue();
4553
4554   SDValue V2 = Elt.getOperand(0);
4555   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4556     V1 = SDValue();
4557
4558   bool CanFold = true;
4559   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4560     if (Zeroable[i])
4561       continue;
4562
4563     SDValue Current = Op->getOperand(i);
4564     SDValue SrcVector = Current->getOperand(0);
4565     if (!V1.getNode())
4566       V1 = SrcVector;
4567     CanFold = SrcVector == V1 &&
4568       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4569   }
4570
4571   if (!CanFold)
4572     return SDValue();
4573
4574   assert(V1.getNode() && "Expected at least two non-zero elements!");
4575   if (V1.getSimpleValueType() != MVT::v4f32)
4576     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4577   if (V2.getSimpleValueType() != MVT::v4f32)
4578     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4579
4580   // Ok, we can emit an INSERTPS instruction.
4581   unsigned ZMask = Zeroable.to_ulong();
4582
4583   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4584   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4585   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4586                                DAG.getIntPtrConstant(InsertPSMask));
4587   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4588 }
4589
4590 /// Return a vector logical shift node.
4591 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4592                          unsigned NumBits, SelectionDAG &DAG,
4593                          const TargetLowering &TLI, SDLoc dl) {
4594   assert(VT.is128BitVector() && "Unknown type for VShift");
4595   MVT ShVT = MVT::v2i64;
4596   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4597   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4598   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4599   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4600   SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4601   return DAG.getNode(ISD::BITCAST, dl, VT,
4602                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4603 }
4604
4605 static SDValue
4606 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4607
4608   // Check if the scalar load can be widened into a vector load. And if
4609   // the address is "base + cst" see if the cst can be "absorbed" into
4610   // the shuffle mask.
4611   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4612     SDValue Ptr = LD->getBasePtr();
4613     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4614       return SDValue();
4615     EVT PVT = LD->getValueType(0);
4616     if (PVT != MVT::i32 && PVT != MVT::f32)
4617       return SDValue();
4618
4619     int FI = -1;
4620     int64_t Offset = 0;
4621     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4622       FI = FINode->getIndex();
4623       Offset = 0;
4624     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4625                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4626       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4627       Offset = Ptr.getConstantOperandVal(1);
4628       Ptr = Ptr.getOperand(0);
4629     } else {
4630       return SDValue();
4631     }
4632
4633     // FIXME: 256-bit vector instructions don't require a strict alignment,
4634     // improve this code to support it better.
4635     unsigned RequiredAlign = VT.getSizeInBits()/8;
4636     SDValue Chain = LD->getChain();
4637     // Make sure the stack object alignment is at least 16 or 32.
4638     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4639     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4640       if (MFI->isFixedObjectIndex(FI)) {
4641         // Can't change the alignment. FIXME: It's possible to compute
4642         // the exact stack offset and reference FI + adjust offset instead.
4643         // If someone *really* cares about this. That's the way to implement it.
4644         return SDValue();
4645       } else {
4646         MFI->setObjectAlignment(FI, RequiredAlign);
4647       }
4648     }
4649
4650     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4651     // Ptr + (Offset & ~15).
4652     if (Offset < 0)
4653       return SDValue();
4654     if ((Offset % RequiredAlign) & 3)
4655       return SDValue();
4656     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4657     if (StartOffset)
4658       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4659                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4660
4661     int EltNo = (Offset - StartOffset) >> 2;
4662     unsigned NumElems = VT.getVectorNumElements();
4663
4664     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4665     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4666                              LD->getPointerInfo().getWithOffset(StartOffset),
4667                              false, false, false, 0);
4668
4669     SmallVector<int, 8> Mask(NumElems, EltNo);
4670
4671     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4672   }
4673
4674   return SDValue();
4675 }
4676
4677 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4678 /// elements can be replaced by a single large load which has the same value as
4679 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4680 ///
4681 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4682 ///
4683 /// FIXME: we'd also like to handle the case where the last elements are zero
4684 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4685 /// There's even a handy isZeroNode for that purpose.
4686 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4687                                         SDLoc &DL, SelectionDAG &DAG,
4688                                         bool isAfterLegalize) {
4689   unsigned NumElems = Elts.size();
4690
4691   LoadSDNode *LDBase = nullptr;
4692   unsigned LastLoadedElt = -1U;
4693
4694   // For each element in the initializer, see if we've found a load or an undef.
4695   // If we don't find an initial load element, or later load elements are
4696   // non-consecutive, bail out.
4697   for (unsigned i = 0; i < NumElems; ++i) {
4698     SDValue Elt = Elts[i];
4699     // Look through a bitcast.
4700     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4701       Elt = Elt.getOperand(0);
4702     if (!Elt.getNode() ||
4703         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4704       return SDValue();
4705     if (!LDBase) {
4706       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4707         return SDValue();
4708       LDBase = cast<LoadSDNode>(Elt.getNode());
4709       LastLoadedElt = i;
4710       continue;
4711     }
4712     if (Elt.getOpcode() == ISD::UNDEF)
4713       continue;
4714
4715     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4716     EVT LdVT = Elt.getValueType();
4717     // Each loaded element must be the correct fractional portion of the
4718     // requested vector load.
4719     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4720       return SDValue();
4721     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4722       return SDValue();
4723     LastLoadedElt = i;
4724   }
4725
4726   // If we have found an entire vector of loads and undefs, then return a large
4727   // load of the entire vector width starting at the base pointer.  If we found
4728   // consecutive loads for the low half, generate a vzext_load node.
4729   if (LastLoadedElt == NumElems - 1) {
4730     assert(LDBase && "Did not find base load for merging consecutive loads");
4731     EVT EltVT = LDBase->getValueType(0);
4732     // Ensure that the input vector size for the merged loads matches the
4733     // cumulative size of the input elements.
4734     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4735       return SDValue();
4736
4737     if (isAfterLegalize &&
4738         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4739       return SDValue();
4740
4741     SDValue NewLd = SDValue();
4742
4743     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4744                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4745                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4746                         LDBase->getAlignment());
4747
4748     if (LDBase->hasAnyUseOfValue(1)) {
4749       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4750                                      SDValue(LDBase, 1),
4751                                      SDValue(NewLd.getNode(), 1));
4752       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4753       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4754                              SDValue(NewLd.getNode(), 1));
4755     }
4756
4757     return NewLd;
4758   }
4759
4760   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4761   //of a v4i32 / v4f32. It's probably worth generalizing.
4762   EVT EltVT = VT.getVectorElementType();
4763   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4764       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4765     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4766     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4767     SDValue ResNode =
4768         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4769                                 LDBase->getPointerInfo(),
4770                                 LDBase->getAlignment(),
4771                                 false/*isVolatile*/, true/*ReadMem*/,
4772                                 false/*WriteMem*/);
4773
4774     // Make sure the newly-created LOAD is in the same position as LDBase in
4775     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4776     // update uses of LDBase's output chain to use the TokenFactor.
4777     if (LDBase->hasAnyUseOfValue(1)) {
4778       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4779                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4780       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4781       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4782                              SDValue(ResNode.getNode(), 1));
4783     }
4784
4785     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4786   }
4787   return SDValue();
4788 }
4789
4790 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4791 /// to generate a splat value for the following cases:
4792 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4793 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4794 /// a scalar load, or a constant.
4795 /// The VBROADCAST node is returned when a pattern is found,
4796 /// or SDValue() otherwise.
4797 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4798                                     SelectionDAG &DAG) {
4799   // VBROADCAST requires AVX.
4800   // TODO: Splats could be generated for non-AVX CPUs using SSE
4801   // instructions, but there's less potential gain for only 128-bit vectors.
4802   if (!Subtarget->hasAVX())
4803     return SDValue();
4804
4805   MVT VT = Op.getSimpleValueType();
4806   SDLoc dl(Op);
4807
4808   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4809          "Unsupported vector type for broadcast.");
4810
4811   SDValue Ld;
4812   bool ConstSplatVal;
4813
4814   switch (Op.getOpcode()) {
4815     default:
4816       // Unknown pattern found.
4817       return SDValue();
4818
4819     case ISD::BUILD_VECTOR: {
4820       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4821       BitVector UndefElements;
4822       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4823
4824       // We need a splat of a single value to use broadcast, and it doesn't
4825       // make any sense if the value is only in one element of the vector.
4826       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4827         return SDValue();
4828
4829       Ld = Splat;
4830       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4831                        Ld.getOpcode() == ISD::ConstantFP);
4832
4833       // Make sure that all of the users of a non-constant load are from the
4834       // BUILD_VECTOR node.
4835       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4836         return SDValue();
4837       break;
4838     }
4839
4840     case ISD::VECTOR_SHUFFLE: {
4841       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4842
4843       // Shuffles must have a splat mask where the first element is
4844       // broadcasted.
4845       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4846         return SDValue();
4847
4848       SDValue Sc = Op.getOperand(0);
4849       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4850           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4851
4852         if (!Subtarget->hasInt256())
4853           return SDValue();
4854
4855         // Use the register form of the broadcast instruction available on AVX2.
4856         if (VT.getSizeInBits() >= 256)
4857           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4858         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4859       }
4860
4861       Ld = Sc.getOperand(0);
4862       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4863                        Ld.getOpcode() == ISD::ConstantFP);
4864
4865       // The scalar_to_vector node and the suspected
4866       // load node must have exactly one user.
4867       // Constants may have multiple users.
4868
4869       // AVX-512 has register version of the broadcast
4870       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4871         Ld.getValueType().getSizeInBits() >= 32;
4872       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4873           !hasRegVer))
4874         return SDValue();
4875       break;
4876     }
4877   }
4878
4879   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4880   bool IsGE256 = (VT.getSizeInBits() >= 256);
4881
4882   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4883   // instruction to save 8 or more bytes of constant pool data.
4884   // TODO: If multiple splats are generated to load the same constant,
4885   // it may be detrimental to overall size. There needs to be a way to detect
4886   // that condition to know if this is truly a size win.
4887   const Function *F = DAG.getMachineFunction().getFunction();
4888   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4889
4890   // Handle broadcasting a single constant scalar from the constant pool
4891   // into a vector.
4892   // On Sandybridge (no AVX2), it is still better to load a constant vector
4893   // from the constant pool and not to broadcast it from a scalar.
4894   // But override that restriction when optimizing for size.
4895   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4896   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4897     EVT CVT = Ld.getValueType();
4898     assert(!CVT.isVector() && "Must not broadcast a vector type");
4899
4900     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4901     // For size optimization, also splat v2f64 and v2i64, and for size opt
4902     // with AVX2, also splat i8 and i16.
4903     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4904     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4905         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4906       const Constant *C = nullptr;
4907       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4908         C = CI->getConstantIntValue();
4909       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4910         C = CF->getConstantFPValue();
4911
4912       assert(C && "Invalid constant type");
4913
4914       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4915       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4916       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4917       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4918                        MachinePointerInfo::getConstantPool(),
4919                        false, false, false, Alignment);
4920
4921       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4922     }
4923   }
4924
4925   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4926
4927   // Handle AVX2 in-register broadcasts.
4928   if (!IsLoad && Subtarget->hasInt256() &&
4929       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4930     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4931
4932   // The scalar source must be a normal load.
4933   if (!IsLoad)
4934     return SDValue();
4935
4936   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4937       (Subtarget->hasVLX() && ScalarSize == 64))
4938     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4939
4940   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4941   // double since there is no vbroadcastsd xmm
4942   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4943     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4944       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4945   }
4946
4947   // Unsupported broadcast.
4948   return SDValue();
4949 }
4950
4951 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4952 /// underlying vector and index.
4953 ///
4954 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4955 /// index.
4956 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4957                                          SDValue ExtIdx) {
4958   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4959   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4960     return Idx;
4961
4962   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4963   // lowered this:
4964   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4965   // to:
4966   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
4967   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
4968   //                           undef)
4969   //                       Constant<0>)
4970   // In this case the vector is the extract_subvector expression and the index
4971   // is 2, as specified by the shuffle.
4972   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4973   SDValue ShuffleVec = SVOp->getOperand(0);
4974   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4975   assert(ShuffleVecVT.getVectorElementType() ==
4976          ExtractedFromVec.getSimpleValueType().getVectorElementType());
4977
4978   int ShuffleIdx = SVOp->getMaskElt(Idx);
4979   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4980     ExtractedFromVec = ShuffleVec;
4981     return ShuffleIdx;
4982   }
4983   return Idx;
4984 }
4985
4986 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4987   MVT VT = Op.getSimpleValueType();
4988
4989   // Skip if insert_vec_elt is not supported.
4990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4991   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
4992     return SDValue();
4993
4994   SDLoc DL(Op);
4995   unsigned NumElems = Op.getNumOperands();
4996
4997   SDValue VecIn1;
4998   SDValue VecIn2;
4999   SmallVector<unsigned, 4> InsertIndices;
5000   SmallVector<int, 8> Mask(NumElems, -1);
5001
5002   for (unsigned i = 0; i != NumElems; ++i) {
5003     unsigned Opc = Op.getOperand(i).getOpcode();
5004
5005     if (Opc == ISD::UNDEF)
5006       continue;
5007
5008     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5009       // Quit if more than 1 elements need inserting.
5010       if (InsertIndices.size() > 1)
5011         return SDValue();
5012
5013       InsertIndices.push_back(i);
5014       continue;
5015     }
5016
5017     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5018     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5019     // Quit if non-constant index.
5020     if (!isa<ConstantSDNode>(ExtIdx))
5021       return SDValue();
5022     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5023
5024     // Quit if extracted from vector of different type.
5025     if (ExtractedFromVec.getValueType() != VT)
5026       return SDValue();
5027
5028     if (!VecIn1.getNode())
5029       VecIn1 = ExtractedFromVec;
5030     else if (VecIn1 != ExtractedFromVec) {
5031       if (!VecIn2.getNode())
5032         VecIn2 = ExtractedFromVec;
5033       else if (VecIn2 != ExtractedFromVec)
5034         // Quit if more than 2 vectors to shuffle
5035         return SDValue();
5036     }
5037
5038     if (ExtractedFromVec == VecIn1)
5039       Mask[i] = Idx;
5040     else if (ExtractedFromVec == VecIn2)
5041       Mask[i] = Idx + NumElems;
5042   }
5043
5044   if (!VecIn1.getNode())
5045     return SDValue();
5046
5047   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5048   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5049   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5050     unsigned Idx = InsertIndices[i];
5051     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5052                      DAG.getIntPtrConstant(Idx));
5053   }
5054
5055   return NV;
5056 }
5057
5058 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5059 SDValue
5060 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5061
5062   MVT VT = Op.getSimpleValueType();
5063   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5064          "Unexpected type in LowerBUILD_VECTORvXi1!");
5065
5066   SDLoc dl(Op);
5067   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5068     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5069     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5070     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5071   }
5072
5073   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5074     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5075     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5076     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5077   }
5078
5079   bool AllContants = true;
5080   uint64_t Immediate = 0;
5081   int NonConstIdx = -1;
5082   bool IsSplat = true;
5083   unsigned NumNonConsts = 0;
5084   unsigned NumConsts = 0;
5085   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5086     SDValue In = Op.getOperand(idx);
5087     if (In.getOpcode() == ISD::UNDEF)
5088       continue;
5089     if (!isa<ConstantSDNode>(In)) {
5090       AllContants = false;
5091       NonConstIdx = idx;
5092       NumNonConsts++;
5093     } else {
5094       NumConsts++;
5095       if (cast<ConstantSDNode>(In)->getZExtValue())
5096       Immediate |= (1ULL << idx);
5097     }
5098     if (In != Op.getOperand(0))
5099       IsSplat = false;
5100   }
5101
5102   if (AllContants) {
5103     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5104       DAG.getConstant(Immediate, MVT::i16));
5105     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5106                        DAG.getIntPtrConstant(0));
5107   }
5108
5109   if (NumNonConsts == 1 && NonConstIdx != 0) {
5110     SDValue DstVec;
5111     if (NumConsts) {
5112       SDValue VecAsImm = DAG.getConstant(Immediate,
5113                                          MVT::getIntegerVT(VT.getSizeInBits()));
5114       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5115     }
5116     else
5117       DstVec = DAG.getUNDEF(VT);
5118     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5119                        Op.getOperand(NonConstIdx),
5120                        DAG.getIntPtrConstant(NonConstIdx));
5121   }
5122   if (!IsSplat && (NonConstIdx != 0))
5123     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5124   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5125   SDValue Select;
5126   if (IsSplat)
5127     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5128                           DAG.getConstant(-1, SelectVT),
5129                           DAG.getConstant(0, SelectVT));
5130   else
5131     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5132                          DAG.getConstant((Immediate | 1), SelectVT),
5133                          DAG.getConstant(Immediate, SelectVT));
5134   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5135 }
5136
5137 /// \brief Return true if \p N implements a horizontal binop and return the
5138 /// operands for the horizontal binop into V0 and V1.
5139 ///
5140 /// This is a helper function of PerformBUILD_VECTORCombine.
5141 /// This function checks that the build_vector \p N in input implements a
5142 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5143 /// operation to match.
5144 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5145 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5146 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5147 /// arithmetic sub.
5148 ///
5149 /// This function only analyzes elements of \p N whose indices are
5150 /// in range [BaseIdx, LastIdx).
5151 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5152                               SelectionDAG &DAG,
5153                               unsigned BaseIdx, unsigned LastIdx,
5154                               SDValue &V0, SDValue &V1) {
5155   EVT VT = N->getValueType(0);
5156
5157   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5158   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5159          "Invalid Vector in input!");
5160
5161   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5162   bool CanFold = true;
5163   unsigned ExpectedVExtractIdx = BaseIdx;
5164   unsigned NumElts = LastIdx - BaseIdx;
5165   V0 = DAG.getUNDEF(VT);
5166   V1 = DAG.getUNDEF(VT);
5167
5168   // Check if N implements a horizontal binop.
5169   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5170     SDValue Op = N->getOperand(i + BaseIdx);
5171
5172     // Skip UNDEFs.
5173     if (Op->getOpcode() == ISD::UNDEF) {
5174       // Update the expected vector extract index.
5175       if (i * 2 == NumElts)
5176         ExpectedVExtractIdx = BaseIdx;
5177       ExpectedVExtractIdx += 2;
5178       continue;
5179     }
5180
5181     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5182
5183     if (!CanFold)
5184       break;
5185
5186     SDValue Op0 = Op.getOperand(0);
5187     SDValue Op1 = Op.getOperand(1);
5188
5189     // Try to match the following pattern:
5190     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5191     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5192         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5193         Op0.getOperand(0) == Op1.getOperand(0) &&
5194         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5195         isa<ConstantSDNode>(Op1.getOperand(1)));
5196     if (!CanFold)
5197       break;
5198
5199     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5200     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5201
5202     if (i * 2 < NumElts) {
5203       if (V0.getOpcode() == ISD::UNDEF)
5204         V0 = Op0.getOperand(0);
5205     } else {
5206       if (V1.getOpcode() == ISD::UNDEF)
5207         V1 = Op0.getOperand(0);
5208       if (i * 2 == NumElts)
5209         ExpectedVExtractIdx = BaseIdx;
5210     }
5211
5212     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5213     if (I0 == ExpectedVExtractIdx)
5214       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5215     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5216       // Try to match the following dag sequence:
5217       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5218       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5219     } else
5220       CanFold = false;
5221
5222     ExpectedVExtractIdx += 2;
5223   }
5224
5225   return CanFold;
5226 }
5227
5228 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5229 /// a concat_vector.
5230 ///
5231 /// This is a helper function of PerformBUILD_VECTORCombine.
5232 /// This function expects two 256-bit vectors called V0 and V1.
5233 /// At first, each vector is split into two separate 128-bit vectors.
5234 /// Then, the resulting 128-bit vectors are used to implement two
5235 /// horizontal binary operations.
5236 ///
5237 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5238 ///
5239 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5240 /// the two new horizontal binop.
5241 /// When Mode is set, the first horizontal binop dag node would take as input
5242 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5243 /// horizontal binop dag node would take as input the lower 128-bit of V1
5244 /// and the upper 128-bit of V1.
5245 ///   Example:
5246 ///     HADD V0_LO, V0_HI
5247 ///     HADD V1_LO, V1_HI
5248 ///
5249 /// Otherwise, the first horizontal binop dag node takes as input the lower
5250 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5251 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5252 ///   Example:
5253 ///     HADD V0_LO, V1_LO
5254 ///     HADD V0_HI, V1_HI
5255 ///
5256 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5257 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5258 /// the upper 128-bits of the result.
5259 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5260                                      SDLoc DL, SelectionDAG &DAG,
5261                                      unsigned X86Opcode, bool Mode,
5262                                      bool isUndefLO, bool isUndefHI) {
5263   EVT VT = V0.getValueType();
5264   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5265          "Invalid nodes in input!");
5266
5267   unsigned NumElts = VT.getVectorNumElements();
5268   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5269   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5270   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5271   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5272   EVT NewVT = V0_LO.getValueType();
5273
5274   SDValue LO = DAG.getUNDEF(NewVT);
5275   SDValue HI = DAG.getUNDEF(NewVT);
5276
5277   if (Mode) {
5278     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5279     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5280       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5281     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5282       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5283   } else {
5284     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5285     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5286                        V1_LO->getOpcode() != ISD::UNDEF))
5287       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5288
5289     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5290                        V1_HI->getOpcode() != ISD::UNDEF))
5291       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5292   }
5293
5294   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5295 }
5296
5297 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5298 /// sequence of 'vadd + vsub + blendi'.
5299 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5300                            const X86Subtarget *Subtarget) {
5301   SDLoc DL(BV);
5302   EVT VT = BV->getValueType(0);
5303   unsigned NumElts = VT.getVectorNumElements();
5304   SDValue InVec0 = DAG.getUNDEF(VT);
5305   SDValue InVec1 = DAG.getUNDEF(VT);
5306
5307   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5308           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5309
5310   // Odd-numbered elements in the input build vector are obtained from
5311   // adding two integer/float elements.
5312   // Even-numbered elements in the input build vector are obtained from
5313   // subtracting two integer/float elements.
5314   unsigned ExpectedOpcode = ISD::FSUB;
5315   unsigned NextExpectedOpcode = ISD::FADD;
5316   bool AddFound = false;
5317   bool SubFound = false;
5318
5319   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5320     SDValue Op = BV->getOperand(i);
5321
5322     // Skip 'undef' values.
5323     unsigned Opcode = Op.getOpcode();
5324     if (Opcode == ISD::UNDEF) {
5325       std::swap(ExpectedOpcode, NextExpectedOpcode);
5326       continue;
5327     }
5328
5329     // Early exit if we found an unexpected opcode.
5330     if (Opcode != ExpectedOpcode)
5331       return SDValue();
5332
5333     SDValue Op0 = Op.getOperand(0);
5334     SDValue Op1 = Op.getOperand(1);
5335
5336     // Try to match the following pattern:
5337     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5338     // Early exit if we cannot match that sequence.
5339     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5340         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5341         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5342         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5343         Op0.getOperand(1) != Op1.getOperand(1))
5344       return SDValue();
5345
5346     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5347     if (I0 != i)
5348       return SDValue();
5349
5350     // We found a valid add/sub node. Update the information accordingly.
5351     if (i & 1)
5352       AddFound = true;
5353     else
5354       SubFound = true;
5355
5356     // Update InVec0 and InVec1.
5357     if (InVec0.getOpcode() == ISD::UNDEF)
5358       InVec0 = Op0.getOperand(0);
5359     if (InVec1.getOpcode() == ISD::UNDEF)
5360       InVec1 = Op1.getOperand(0);
5361
5362     // Make sure that operands in input to each add/sub node always
5363     // come from a same pair of vectors.
5364     if (InVec0 != Op0.getOperand(0)) {
5365       if (ExpectedOpcode == ISD::FSUB)
5366         return SDValue();
5367
5368       // FADD is commutable. Try to commute the operands
5369       // and then test again.
5370       std::swap(Op0, Op1);
5371       if (InVec0 != Op0.getOperand(0))
5372         return SDValue();
5373     }
5374
5375     if (InVec1 != Op1.getOperand(0))
5376       return SDValue();
5377
5378     // Update the pair of expected opcodes.
5379     std::swap(ExpectedOpcode, NextExpectedOpcode);
5380   }
5381
5382   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5383   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5384       InVec1.getOpcode() != ISD::UNDEF)
5385     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5386
5387   return SDValue();
5388 }
5389
5390 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5391                                           const X86Subtarget *Subtarget) {
5392   SDLoc DL(N);
5393   EVT VT = N->getValueType(0);
5394   unsigned NumElts = VT.getVectorNumElements();
5395   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5396   SDValue InVec0, InVec1;
5397
5398   // Try to match an ADDSUB.
5399   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5400       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5401     SDValue Value = matchAddSub(BV, DAG, Subtarget);
5402     if (Value.getNode())
5403       return Value;
5404   }
5405
5406   // Try to match horizontal ADD/SUB.
5407   unsigned NumUndefsLO = 0;
5408   unsigned NumUndefsHI = 0;
5409   unsigned Half = NumElts/2;
5410
5411   // Count the number of UNDEF operands in the build_vector in input.
5412   for (unsigned i = 0, e = Half; i != e; ++i)
5413     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5414       NumUndefsLO++;
5415
5416   for (unsigned i = Half, e = NumElts; i != e; ++i)
5417     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5418       NumUndefsHI++;
5419
5420   // Early exit if this is either a build_vector of all UNDEFs or all the
5421   // operands but one are UNDEF.
5422   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5423     return SDValue();
5424
5425   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5426     // Try to match an SSE3 float HADD/HSUB.
5427     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5428       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5429
5430     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5431       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5432   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5433     // Try to match an SSSE3 integer HADD/HSUB.
5434     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5435       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5436
5437     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5438       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5439   }
5440
5441   if (!Subtarget->hasAVX())
5442     return SDValue();
5443
5444   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5445     // Try to match an AVX horizontal add/sub of packed single/double
5446     // precision floating point values from 256-bit vectors.
5447     SDValue InVec2, InVec3;
5448     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5449         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5450         ((InVec0.getOpcode() == ISD::UNDEF ||
5451           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5452         ((InVec1.getOpcode() == ISD::UNDEF ||
5453           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5454       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5455
5456     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5457         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5458         ((InVec0.getOpcode() == ISD::UNDEF ||
5459           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5460         ((InVec1.getOpcode() == ISD::UNDEF ||
5461           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5462       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5463   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5464     // Try to match an AVX2 horizontal add/sub of signed integers.
5465     SDValue InVec2, InVec3;
5466     unsigned X86Opcode;
5467     bool CanFold = true;
5468
5469     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5470         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5471         ((InVec0.getOpcode() == ISD::UNDEF ||
5472           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5473         ((InVec1.getOpcode() == ISD::UNDEF ||
5474           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5475       X86Opcode = X86ISD::HADD;
5476     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5477         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5478         ((InVec0.getOpcode() == ISD::UNDEF ||
5479           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5480         ((InVec1.getOpcode() == ISD::UNDEF ||
5481           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5482       X86Opcode = X86ISD::HSUB;
5483     else
5484       CanFold = false;
5485
5486     if (CanFold) {
5487       // Fold this build_vector into a single horizontal add/sub.
5488       // Do this only if the target has AVX2.
5489       if (Subtarget->hasAVX2())
5490         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5491
5492       // Do not try to expand this build_vector into a pair of horizontal
5493       // add/sub if we can emit a pair of scalar add/sub.
5494       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5495         return SDValue();
5496
5497       // Convert this build_vector into a pair of horizontal binop followed by
5498       // a concat vector.
5499       bool isUndefLO = NumUndefsLO == Half;
5500       bool isUndefHI = NumUndefsHI == Half;
5501       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5502                                    isUndefLO, isUndefHI);
5503     }
5504   }
5505
5506   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5507        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5508     unsigned X86Opcode;
5509     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5510       X86Opcode = X86ISD::HADD;
5511     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5512       X86Opcode = X86ISD::HSUB;
5513     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5514       X86Opcode = X86ISD::FHADD;
5515     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5516       X86Opcode = X86ISD::FHSUB;
5517     else
5518       return SDValue();
5519
5520     // Don't try to expand this build_vector into a pair of horizontal add/sub
5521     // if we can simply emit a pair of scalar add/sub.
5522     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5523       return SDValue();
5524
5525     // Convert this build_vector into two horizontal add/sub followed by
5526     // a concat vector.
5527     bool isUndefLO = NumUndefsLO == Half;
5528     bool isUndefHI = NumUndefsHI == Half;
5529     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5530                                  isUndefLO, isUndefHI);
5531   }
5532
5533   return SDValue();
5534 }
5535
5536 SDValue
5537 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5538   SDLoc dl(Op);
5539
5540   MVT VT = Op.getSimpleValueType();
5541   MVT ExtVT = VT.getVectorElementType();
5542   unsigned NumElems = Op.getNumOperands();
5543
5544   // Generate vectors for predicate vectors.
5545   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5546     return LowerBUILD_VECTORvXi1(Op, DAG);
5547
5548   // Vectors containing all zeros can be matched by pxor and xorps later
5549   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5550     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5551     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5552     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5553       return Op;
5554
5555     return getZeroVector(VT, Subtarget, DAG, dl);
5556   }
5557
5558   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5559   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5560   // vpcmpeqd on 256-bit vectors.
5561   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5562     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5563       return Op;
5564
5565     if (!VT.is512BitVector())
5566       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5567   }
5568
5569   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5570   if (Broadcast.getNode())
5571     return Broadcast;
5572
5573   unsigned EVTBits = ExtVT.getSizeInBits();
5574
5575   unsigned NumZero  = 0;
5576   unsigned NumNonZero = 0;
5577   unsigned NonZeros = 0;
5578   bool IsAllConstants = true;
5579   SmallSet<SDValue, 8> Values;
5580   for (unsigned i = 0; i < NumElems; ++i) {
5581     SDValue Elt = Op.getOperand(i);
5582     if (Elt.getOpcode() == ISD::UNDEF)
5583       continue;
5584     Values.insert(Elt);
5585     if (Elt.getOpcode() != ISD::Constant &&
5586         Elt.getOpcode() != ISD::ConstantFP)
5587       IsAllConstants = false;
5588     if (X86::isZeroNode(Elt))
5589       NumZero++;
5590     else {
5591       NonZeros |= (1 << i);
5592       NumNonZero++;
5593     }
5594   }
5595
5596   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5597   if (NumNonZero == 0)
5598     return DAG.getUNDEF(VT);
5599
5600   // Special case for single non-zero, non-undef, element.
5601   if (NumNonZero == 1) {
5602     unsigned Idx = countTrailingZeros(NonZeros);
5603     SDValue Item = Op.getOperand(Idx);
5604
5605     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5606     // the value are obviously zero, truncate the value to i32 and do the
5607     // insertion that way.  Only do this if the value is non-constant or if the
5608     // value is a constant being inserted into element 0.  It is cheaper to do
5609     // a constant pool load than it is to do a movd + shuffle.
5610     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5611         (!IsAllConstants || Idx == 0)) {
5612       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5613         // Handle SSE only.
5614         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5615         EVT VecVT = MVT::v4i32;
5616
5617         // Truncate the value (which may itself be a constant) to i32, and
5618         // convert it to a vector with movd (S2V+shuffle to zero extend).
5619         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5620         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5621         return DAG.getNode(
5622             ISD::BITCAST, dl, VT,
5623             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5624       }
5625     }
5626
5627     // If we have a constant or non-constant insertion into the low element of
5628     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5629     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5630     // depending on what the source datatype is.
5631     if (Idx == 0) {
5632       if (NumZero == 0)
5633         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5634
5635       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5636           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5637         if (VT.is256BitVector() || VT.is512BitVector()) {
5638           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5639           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5640                              Item, DAG.getIntPtrConstant(0));
5641         }
5642         assert(VT.is128BitVector() && "Expected an SSE value type!");
5643         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5644         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5645         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5646       }
5647
5648       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5649         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5650         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5651         if (VT.is256BitVector()) {
5652           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5653           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5654         } else {
5655           assert(VT.is128BitVector() && "Expected an SSE value type!");
5656           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5657         }
5658         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5659       }
5660     }
5661
5662     // Is it a vector logical left shift?
5663     if (NumElems == 2 && Idx == 1 &&
5664         X86::isZeroNode(Op.getOperand(0)) &&
5665         !X86::isZeroNode(Op.getOperand(1))) {
5666       unsigned NumBits = VT.getSizeInBits();
5667       return getVShift(true, VT,
5668                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5669                                    VT, Op.getOperand(1)),
5670                        NumBits/2, DAG, *this, dl);
5671     }
5672
5673     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5674       return SDValue();
5675
5676     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5677     // is a non-constant being inserted into an element other than the low one,
5678     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5679     // movd/movss) to move this into the low element, then shuffle it into
5680     // place.
5681     if (EVTBits == 32) {
5682       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5683       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5684     }
5685   }
5686
5687   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5688   if (Values.size() == 1) {
5689     if (EVTBits == 32) {
5690       // Instead of a shuffle like this:
5691       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5692       // Check if it's possible to issue this instead.
5693       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5694       unsigned Idx = countTrailingZeros(NonZeros);
5695       SDValue Item = Op.getOperand(Idx);
5696       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5697         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5698     }
5699     return SDValue();
5700   }
5701
5702   // A vector full of immediates; various special cases are already
5703   // handled, so this is best done with a single constant-pool load.
5704   if (IsAllConstants)
5705     return SDValue();
5706
5707   // For AVX-length vectors, see if we can use a vector load to get all of the
5708   // elements, otherwise build the individual 128-bit pieces and use
5709   // shuffles to put them in place.
5710   if (VT.is256BitVector() || VT.is512BitVector()) {
5711     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5712
5713     // Check for a build vector of consecutive loads.
5714     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5715       return LD;
5716
5717     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5718
5719     // Build both the lower and upper subvector.
5720     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5721                                 makeArrayRef(&V[0], NumElems/2));
5722     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5723                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5724
5725     // Recreate the wider vector with the lower and upper part.
5726     if (VT.is256BitVector())
5727       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5728     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5729   }
5730
5731   // Let legalizer expand 2-wide build_vectors.
5732   if (EVTBits == 64) {
5733     if (NumNonZero == 1) {
5734       // One half is zero or undef.
5735       unsigned Idx = countTrailingZeros(NonZeros);
5736       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5737                                  Op.getOperand(Idx));
5738       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5739     }
5740     return SDValue();
5741   }
5742
5743   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5744   if (EVTBits == 8 && NumElems == 16) {
5745     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5746                                         Subtarget, *this);
5747     if (V.getNode()) return V;
5748   }
5749
5750   if (EVTBits == 16 && NumElems == 8) {
5751     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5752                                       Subtarget, *this);
5753     if (V.getNode()) return V;
5754   }
5755
5756   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5757   if (EVTBits == 32 && NumElems == 4) {
5758     SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
5759     if (V.getNode())
5760       return V;
5761   }
5762
5763   // If element VT is == 32 bits, turn it into a number of shuffles.
5764   SmallVector<SDValue, 8> V(NumElems);
5765   if (NumElems == 4 && NumZero > 0) {
5766     for (unsigned i = 0; i < 4; ++i) {
5767       bool isZero = !(NonZeros & (1 << i));
5768       if (isZero)
5769         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5770       else
5771         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5772     }
5773
5774     for (unsigned i = 0; i < 2; ++i) {
5775       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5776         default: break;
5777         case 0:
5778           V[i] = V[i*2];  // Must be a zero vector.
5779           break;
5780         case 1:
5781           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5782           break;
5783         case 2:
5784           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5785           break;
5786         case 3:
5787           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5788           break;
5789       }
5790     }
5791
5792     bool Reverse1 = (NonZeros & 0x3) == 2;
5793     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5794     int MaskVec[] = {
5795       Reverse1 ? 1 : 0,
5796       Reverse1 ? 0 : 1,
5797       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5798       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5799     };
5800     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5801   }
5802
5803   if (Values.size() > 1 && VT.is128BitVector()) {
5804     // Check for a build vector of consecutive loads.
5805     for (unsigned i = 0; i < NumElems; ++i)
5806       V[i] = Op.getOperand(i);
5807
5808     // Check for elements which are consecutive loads.
5809     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
5810     if (LD.getNode())
5811       return LD;
5812
5813     // Check for a build vector from mostly shuffle plus few inserting.
5814     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5815     if (Sh.getNode())
5816       return Sh;
5817
5818     // For SSE 4.1, use insertps to put the high elements into the low element.
5819     if (Subtarget->hasSSE41()) {
5820       SDValue Result;
5821       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5822         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5823       else
5824         Result = DAG.getUNDEF(VT);
5825
5826       for (unsigned i = 1; i < NumElems; ++i) {
5827         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5828         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5829                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5830       }
5831       return Result;
5832     }
5833
5834     // Otherwise, expand into a number of unpckl*, start by extending each of
5835     // our (non-undef) elements to the full vector width with the element in the
5836     // bottom slot of the vector (which generates no code for SSE).
5837     for (unsigned i = 0; i < NumElems; ++i) {
5838       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5839         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5840       else
5841         V[i] = DAG.getUNDEF(VT);
5842     }
5843
5844     // Next, we iteratively mix elements, e.g. for v4f32:
5845     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5846     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5847     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5848     unsigned EltStride = NumElems >> 1;
5849     while (EltStride != 0) {
5850       for (unsigned i = 0; i < EltStride; ++i) {
5851         // If V[i+EltStride] is undef and this is the first round of mixing,
5852         // then it is safe to just drop this shuffle: V[i] is already in the
5853         // right place, the one element (since it's the first round) being
5854         // inserted as undef can be dropped.  This isn't safe for successive
5855         // rounds because they will permute elements within both vectors.
5856         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5857             EltStride == NumElems/2)
5858           continue;
5859
5860         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5861       }
5862       EltStride >>= 1;
5863     }
5864     return V[0];
5865   }
5866   return SDValue();
5867 }
5868
5869 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5870 // to create 256-bit vectors from two other 128-bit ones.
5871 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5872   SDLoc dl(Op);
5873   MVT ResVT = Op.getSimpleValueType();
5874
5875   assert((ResVT.is256BitVector() ||
5876           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5877
5878   SDValue V1 = Op.getOperand(0);
5879   SDValue V2 = Op.getOperand(1);
5880   unsigned NumElems = ResVT.getVectorNumElements();
5881   if(ResVT.is256BitVector())
5882     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5883
5884   if (Op.getNumOperands() == 4) {
5885     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5886                                 ResVT.getVectorNumElements()/2);
5887     SDValue V3 = Op.getOperand(2);
5888     SDValue V4 = Op.getOperand(3);
5889     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5890       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5891   }
5892   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5893 }
5894
5895 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5896   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
5897   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5898          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5899           Op.getNumOperands() == 4)));
5900
5901   // AVX can use the vinsertf128 instruction to create 256-bit vectors
5902   // from two other 128-bit ones.
5903
5904   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5905   return LowerAVXCONCAT_VECTORS(Op, DAG);
5906 }
5907
5908
5909 //===----------------------------------------------------------------------===//
5910 // Vector shuffle lowering
5911 //
5912 // This is an experimental code path for lowering vector shuffles on x86. It is
5913 // designed to handle arbitrary vector shuffles and blends, gracefully
5914 // degrading performance as necessary. It works hard to recognize idiomatic
5915 // shuffles and lower them to optimal instruction patterns without leaving
5916 // a framework that allows reasonably efficient handling of all vector shuffle
5917 // patterns.
5918 //===----------------------------------------------------------------------===//
5919
5920 /// \brief Tiny helper function to identify a no-op mask.
5921 ///
5922 /// This is a somewhat boring predicate function. It checks whether the mask
5923 /// array input, which is assumed to be a single-input shuffle mask of the kind
5924 /// used by the X86 shuffle instructions (not a fully general
5925 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5926 /// in-place shuffle are 'no-op's.
5927 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5928   for (int i = 0, Size = Mask.size(); i < Size; ++i)
5929     if (Mask[i] != -1 && Mask[i] != i)
5930       return false;
5931   return true;
5932 }
5933
5934 /// \brief Helper function to classify a mask as a single-input mask.
5935 ///
5936 /// This isn't a generic single-input test because in the vector shuffle
5937 /// lowering we canonicalize single inputs to be the first input operand. This
5938 /// means we can more quickly test for a single input by only checking whether
5939 /// an input from the second operand exists. We also assume that the size of
5940 /// mask corresponds to the size of the input vectors which isn't true in the
5941 /// fully general case.
5942 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
5943   for (int M : Mask)
5944     if (M >= (int)Mask.size())
5945       return false;
5946   return true;
5947 }
5948
5949 /// \brief Test whether there are elements crossing 128-bit lanes in this
5950 /// shuffle mask.
5951 ///
5952 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
5953 /// and we routinely test for these.
5954 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
5955   int LaneSize = 128 / VT.getScalarSizeInBits();
5956   int Size = Mask.size();
5957   for (int i = 0; i < Size; ++i)
5958     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
5959       return true;
5960   return false;
5961 }
5962
5963 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
5964 ///
5965 /// This checks a shuffle mask to see if it is performing the same
5966 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
5967 /// that it is also not lane-crossing. It may however involve a blend from the
5968 /// same lane of a second vector.
5969 ///
5970 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
5971 /// non-trivial to compute in the face of undef lanes. The representation is
5972 /// *not* suitable for use with existing 128-bit shuffles as it will contain
5973 /// entries from both V1 and V2 inputs to the wider mask.
5974 static bool
5975 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
5976                                 SmallVectorImpl<int> &RepeatedMask) {
5977   int LaneSize = 128 / VT.getScalarSizeInBits();
5978   RepeatedMask.resize(LaneSize, -1);
5979   int Size = Mask.size();
5980   for (int i = 0; i < Size; ++i) {
5981     if (Mask[i] < 0)
5982       continue;
5983     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
5984       // This entry crosses lanes, so there is no way to model this shuffle.
5985       return false;
5986
5987     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
5988     if (RepeatedMask[i % LaneSize] == -1)
5989       // This is the first non-undef entry in this slot of a 128-bit lane.
5990       RepeatedMask[i % LaneSize] =
5991           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
5992     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
5993       // Found a mismatch with the repeated mask.
5994       return false;
5995   }
5996   return true;
5997 }
5998
5999 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6000 /// arguments.
6001 ///
6002 /// This is a fast way to test a shuffle mask against a fixed pattern:
6003 ///
6004 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6005 ///
6006 /// It returns true if the mask is exactly as wide as the argument list, and
6007 /// each element of the mask is either -1 (signifying undef) or the value given
6008 /// in the argument.
6009 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6010                                 ArrayRef<int> ExpectedMask) {
6011   if (Mask.size() != ExpectedMask.size())
6012     return false;
6013
6014   int Size = Mask.size();
6015
6016   // If the values are build vectors, we can look through them to find
6017   // equivalent inputs that make the shuffles equivalent.
6018   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6019   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6020
6021   for (int i = 0; i < Size; ++i)
6022     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6023       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6024       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6025       if (!MaskBV || !ExpectedBV ||
6026           MaskBV->getOperand(Mask[i] % Size) !=
6027               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6028         return false;
6029     }
6030
6031   return true;
6032 }
6033
6034 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6035 ///
6036 /// This helper function produces an 8-bit shuffle immediate corresponding to
6037 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6038 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6039 /// example.
6040 ///
6041 /// NB: We rely heavily on "undef" masks preserving the input lane.
6042 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6043                                           SelectionDAG &DAG) {
6044   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6045   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6046   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6047   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6048   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6049
6050   unsigned Imm = 0;
6051   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6052   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6053   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6054   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6055   return DAG.getConstant(Imm, MVT::i8);
6056 }
6057
6058 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6059 ///
6060 /// This is used as a fallback approach when first class blend instructions are
6061 /// unavailable. Currently it is only suitable for integer vectors, but could
6062 /// be generalized for floating point vectors if desirable.
6063 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6064                                             SDValue V2, ArrayRef<int> Mask,
6065                                             SelectionDAG &DAG) {
6066   assert(VT.isInteger() && "Only supports integer vector types!");
6067   MVT EltVT = VT.getScalarType();
6068   int NumEltBits = EltVT.getSizeInBits();
6069   SDValue Zero = DAG.getConstant(0, EltVT);
6070   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6071   SmallVector<SDValue, 16> MaskOps;
6072   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6073     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6074       return SDValue(); // Shuffled input!
6075     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6076   }
6077
6078   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6079   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6080   // We have to cast V2 around.
6081   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6082   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6083                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6084                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6085                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6086   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6087 }
6088
6089 /// \brief Try to emit a blend instruction for a shuffle.
6090 ///
6091 /// This doesn't do any checks for the availability of instructions for blending
6092 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6093 /// be matched in the backend with the type given. What it does check for is
6094 /// that the shuffle mask is in fact a blend.
6095 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6096                                          SDValue V2, ArrayRef<int> Mask,
6097                                          const X86Subtarget *Subtarget,
6098                                          SelectionDAG &DAG) {
6099   unsigned BlendMask = 0;
6100   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6101     if (Mask[i] >= Size) {
6102       if (Mask[i] != i + Size)
6103         return SDValue(); // Shuffled V2 input!
6104       BlendMask |= 1u << i;
6105       continue;
6106     }
6107     if (Mask[i] >= 0 && Mask[i] != i)
6108       return SDValue(); // Shuffled V1 input!
6109   }
6110   switch (VT.SimpleTy) {
6111   case MVT::v2f64:
6112   case MVT::v4f32:
6113   case MVT::v4f64:
6114   case MVT::v8f32:
6115     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6116                        DAG.getConstant(BlendMask, MVT::i8));
6117
6118   case MVT::v4i64:
6119   case MVT::v8i32:
6120     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6121     // FALLTHROUGH
6122   case MVT::v2i64:
6123   case MVT::v4i32:
6124     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6125     // that instruction.
6126     if (Subtarget->hasAVX2()) {
6127       // Scale the blend by the number of 32-bit dwords per element.
6128       int Scale =  VT.getScalarSizeInBits() / 32;
6129       BlendMask = 0;
6130       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6131         if (Mask[i] >= Size)
6132           for (int j = 0; j < Scale; ++j)
6133             BlendMask |= 1u << (i * Scale + j);
6134
6135       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6136       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6137       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6138       return DAG.getNode(ISD::BITCAST, DL, VT,
6139                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6140                                      DAG.getConstant(BlendMask, MVT::i8)));
6141     }
6142     // FALLTHROUGH
6143   case MVT::v8i16: {
6144     // For integer shuffles we need to expand the mask and cast the inputs to
6145     // v8i16s prior to blending.
6146     int Scale = 8 / VT.getVectorNumElements();
6147     BlendMask = 0;
6148     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6149       if (Mask[i] >= Size)
6150         for (int j = 0; j < Scale; ++j)
6151           BlendMask |= 1u << (i * Scale + j);
6152
6153     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6154     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6155     return DAG.getNode(ISD::BITCAST, DL, VT,
6156                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6157                                    DAG.getConstant(BlendMask, MVT::i8)));
6158   }
6159
6160   case MVT::v16i16: {
6161     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6162     SmallVector<int, 8> RepeatedMask;
6163     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6164       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6165       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6166       BlendMask = 0;
6167       for (int i = 0; i < 8; ++i)
6168         if (RepeatedMask[i] >= 16)
6169           BlendMask |= 1u << i;
6170       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6171                          DAG.getConstant(BlendMask, MVT::i8));
6172     }
6173   }
6174     // FALLTHROUGH
6175   case MVT::v16i8:
6176   case MVT::v32i8: {
6177     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6178            "256-bit byte-blends require AVX2 support!");
6179
6180     // Scale the blend by the number of bytes per element.
6181     int Scale = VT.getScalarSizeInBits() / 8;
6182
6183     // This form of blend is always done on bytes. Compute the byte vector
6184     // type.
6185     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6186
6187     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6188     // mix of LLVM's code generator and the x86 backend. We tell the code
6189     // generator that boolean values in the elements of an x86 vector register
6190     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6191     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6192     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6193     // of the element (the remaining are ignored) and 0 in that high bit would
6194     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6195     // the LLVM model for boolean values in vector elements gets the relevant
6196     // bit set, it is set backwards and over constrained relative to x86's
6197     // actual model.
6198     SmallVector<SDValue, 32> VSELECTMask;
6199     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6200       for (int j = 0; j < Scale; ++j)
6201         VSELECTMask.push_back(
6202             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6203                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6204
6205     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6206     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6207     return DAG.getNode(
6208         ISD::BITCAST, DL, VT,
6209         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6210                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6211                     V1, V2));
6212   }
6213
6214   default:
6215     llvm_unreachable("Not a supported integer vector type!");
6216   }
6217 }
6218
6219 /// \brief Try to lower as a blend of elements from two inputs followed by
6220 /// a single-input permutation.
6221 ///
6222 /// This matches the pattern where we can blend elements from two inputs and
6223 /// then reduce the shuffle to a single-input permutation.
6224 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6225                                                    SDValue V2,
6226                                                    ArrayRef<int> Mask,
6227                                                    SelectionDAG &DAG) {
6228   // We build up the blend mask while checking whether a blend is a viable way
6229   // to reduce the shuffle.
6230   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6231   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6232
6233   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6234     if (Mask[i] < 0)
6235       continue;
6236
6237     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6238
6239     if (BlendMask[Mask[i] % Size] == -1)
6240       BlendMask[Mask[i] % Size] = Mask[i];
6241     else if (BlendMask[Mask[i] % Size] != Mask[i])
6242       return SDValue(); // Can't blend in the needed input!
6243
6244     PermuteMask[i] = Mask[i] % Size;
6245   }
6246
6247   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6248   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6249 }
6250
6251 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6252 /// blends and permutes.
6253 ///
6254 /// This matches the extremely common pattern for handling combined
6255 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6256 /// operations. It will try to pick the best arrangement of shuffles and
6257 /// blends.
6258 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6259                                                           SDValue V1,
6260                                                           SDValue V2,
6261                                                           ArrayRef<int> Mask,
6262                                                           SelectionDAG &DAG) {
6263   // Shuffle the input elements into the desired positions in V1 and V2 and
6264   // blend them together.
6265   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6266   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6267   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6268   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6269     if (Mask[i] >= 0 && Mask[i] < Size) {
6270       V1Mask[i] = Mask[i];
6271       BlendMask[i] = i;
6272     } else if (Mask[i] >= Size) {
6273       V2Mask[i] = Mask[i] - Size;
6274       BlendMask[i] = i + Size;
6275     }
6276
6277   // Try to lower with the simpler initial blend strategy unless one of the
6278   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6279   // shuffle may be able to fold with a load or other benefit. However, when
6280   // we'll have to do 2x as many shuffles in order to achieve this, blending
6281   // first is a better strategy.
6282   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6283     if (SDValue BlendPerm =
6284             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6285       return BlendPerm;
6286
6287   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6288   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6289   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6290 }
6291
6292 /// \brief Try to lower a vector shuffle as a byte rotation.
6293 ///
6294 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6295 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6296 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6297 /// try to generically lower a vector shuffle through such an pattern. It
6298 /// does not check for the profitability of lowering either as PALIGNR or
6299 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6300 /// This matches shuffle vectors that look like:
6301 ///
6302 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6303 ///
6304 /// Essentially it concatenates V1 and V2, shifts right by some number of
6305 /// elements, and takes the low elements as the result. Note that while this is
6306 /// specified as a *right shift* because x86 is little-endian, it is a *left
6307 /// rotate* of the vector lanes.
6308 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6309                                               SDValue V2,
6310                                               ArrayRef<int> Mask,
6311                                               const X86Subtarget *Subtarget,
6312                                               SelectionDAG &DAG) {
6313   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6314
6315   int NumElts = Mask.size();
6316   int NumLanes = VT.getSizeInBits() / 128;
6317   int NumLaneElts = NumElts / NumLanes;
6318
6319   // We need to detect various ways of spelling a rotation:
6320   //   [11, 12, 13, 14, 15,  0,  1,  2]
6321   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6322   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6323   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6324   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6325   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6326   int Rotation = 0;
6327   SDValue Lo, Hi;
6328   for (int l = 0; l < NumElts; l += NumLaneElts) {
6329     for (int i = 0; i < NumLaneElts; ++i) {
6330       if (Mask[l + i] == -1)
6331         continue;
6332       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6333
6334       // Get the mod-Size index and lane correct it.
6335       int LaneIdx = (Mask[l + i] % NumElts) - l;
6336       // Make sure it was in this lane.
6337       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6338         return SDValue();
6339
6340       // Determine where a rotated vector would have started.
6341       int StartIdx = i - LaneIdx;
6342       if (StartIdx == 0)
6343         // The identity rotation isn't interesting, stop.
6344         return SDValue();
6345
6346       // If we found the tail of a vector the rotation must be the missing
6347       // front. If we found the head of a vector, it must be how much of the
6348       // head.
6349       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6350
6351       if (Rotation == 0)
6352         Rotation = CandidateRotation;
6353       else if (Rotation != CandidateRotation)
6354         // The rotations don't match, so we can't match this mask.
6355         return SDValue();
6356
6357       // Compute which value this mask is pointing at.
6358       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6359
6360       // Compute which of the two target values this index should be assigned
6361       // to. This reflects whether the high elements are remaining or the low
6362       // elements are remaining.
6363       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6364
6365       // Either set up this value if we've not encountered it before, or check
6366       // that it remains consistent.
6367       if (!TargetV)
6368         TargetV = MaskV;
6369       else if (TargetV != MaskV)
6370         // This may be a rotation, but it pulls from the inputs in some
6371         // unsupported interleaving.
6372         return SDValue();
6373     }
6374   }
6375
6376   // Check that we successfully analyzed the mask, and normalize the results.
6377   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6378   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6379   if (!Lo)
6380     Lo = Hi;
6381   else if (!Hi)
6382     Hi = Lo;
6383
6384   // The actual rotate instruction rotates bytes, so we need to scale the
6385   // rotation based on how many bytes are in the vector lane.
6386   int Scale = 16 / NumLaneElts;
6387
6388   // SSSE3 targets can use the palignr instruction.
6389   if (Subtarget->hasSSSE3()) {
6390     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6391     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6392     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6393     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6394
6395     return DAG.getNode(ISD::BITCAST, DL, VT,
6396                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6397                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
6398   }
6399
6400   assert(VT.getSizeInBits() == 128 &&
6401          "Rotate-based lowering only supports 128-bit lowering!");
6402   assert(Mask.size() <= 16 &&
6403          "Can shuffle at most 16 bytes in a 128-bit vector!");
6404
6405   // Default SSE2 implementation
6406   int LoByteShift = 16 - Rotation * Scale;
6407   int HiByteShift = Rotation * Scale;
6408
6409   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6410   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6411   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6412
6413   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6414                                 DAG.getConstant(LoByteShift, MVT::i8));
6415   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6416                                 DAG.getConstant(HiByteShift, MVT::i8));
6417   return DAG.getNode(ISD::BITCAST, DL, VT,
6418                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6419 }
6420
6421 /// \brief Compute whether each element of a shuffle is zeroable.
6422 ///
6423 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6424 /// Either it is an undef element in the shuffle mask, the element of the input
6425 /// referenced is undef, or the element of the input referenced is known to be
6426 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6427 /// as many lanes with this technique as possible to simplify the remaining
6428 /// shuffle.
6429 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6430                                                      SDValue V1, SDValue V2) {
6431   SmallBitVector Zeroable(Mask.size(), false);
6432
6433   while (V1.getOpcode() == ISD::BITCAST)
6434     V1 = V1->getOperand(0);
6435   while (V2.getOpcode() == ISD::BITCAST)
6436     V2 = V2->getOperand(0);
6437
6438   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6439   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6440
6441   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6442     int M = Mask[i];
6443     // Handle the easy cases.
6444     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6445       Zeroable[i] = true;
6446       continue;
6447     }
6448
6449     // If this is an index into a build_vector node (which has the same number
6450     // of elements), dig out the input value and use it.
6451     SDValue V = M < Size ? V1 : V2;
6452     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6453       continue;
6454
6455     SDValue Input = V.getOperand(M % Size);
6456     // The UNDEF opcode check really should be dead code here, but not quite
6457     // worth asserting on (it isn't invalid, just unexpected).
6458     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6459       Zeroable[i] = true;
6460   }
6461
6462   return Zeroable;
6463 }
6464
6465 /// \brief Try to emit a bitmask instruction for a shuffle.
6466 ///
6467 /// This handles cases where we can model a blend exactly as a bitmask due to
6468 /// one of the inputs being zeroable.
6469 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6470                                            SDValue V2, ArrayRef<int> Mask,
6471                                            SelectionDAG &DAG) {
6472   MVT EltVT = VT.getScalarType();
6473   int NumEltBits = EltVT.getSizeInBits();
6474   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6475   SDValue Zero = DAG.getConstant(0, IntEltVT);
6476   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6477   if (EltVT.isFloatingPoint()) {
6478     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6479     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6480   }
6481   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6482   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6483   SDValue V;
6484   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6485     if (Zeroable[i])
6486       continue;
6487     if (Mask[i] % Size != i)
6488       return SDValue(); // Not a blend.
6489     if (!V)
6490       V = Mask[i] < Size ? V1 : V2;
6491     else if (V != (Mask[i] < Size ? V1 : V2))
6492       return SDValue(); // Can only let one input through the mask.
6493
6494     VMaskOps[i] = AllOnes;
6495   }
6496   if (!V)
6497     return SDValue(); // No non-zeroable elements!
6498
6499   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6500   V = DAG.getNode(VT.isFloatingPoint()
6501                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6502                   DL, VT, V, VMask);
6503   return V;
6504 }
6505
6506 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6507 ///
6508 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6509 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6510 /// matches elements from one of the input vectors shuffled to the left or
6511 /// right with zeroable elements 'shifted in'. It handles both the strictly
6512 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6513 /// quad word lane.
6514 ///
6515 /// PSHL : (little-endian) left bit shift.
6516 /// [ zz, 0, zz,  2 ]
6517 /// [ -1, 4, zz, -1 ]
6518 /// PSRL : (little-endian) right bit shift.
6519 /// [  1, zz,  3, zz]
6520 /// [ -1, -1,  7, zz]
6521 /// PSLLDQ : (little-endian) left byte shift
6522 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6523 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6524 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6525 /// PSRLDQ : (little-endian) right byte shift
6526 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6527 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6528 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6529 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6530                                          SDValue V2, ArrayRef<int> Mask,
6531                                          SelectionDAG &DAG) {
6532   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6533
6534   int Size = Mask.size();
6535   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6536
6537   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6538     for (int i = 0; i < Size; i += Scale)
6539       for (int j = 0; j < Shift; ++j)
6540         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6541           return false;
6542
6543     return true;
6544   };
6545
6546   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6547     for (int i = 0; i != Size; i += Scale) {
6548       unsigned Pos = Left ? i + Shift : i;
6549       unsigned Low = Left ? i : i + Shift;
6550       unsigned Len = Scale - Shift;
6551       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6552                                       Low + (V == V1 ? 0 : Size)))
6553         return SDValue();
6554     }
6555
6556     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6557     bool ByteShift = ShiftEltBits > 64;
6558     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6559                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6560     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6561
6562     // Normalize the scale for byte shifts to still produce an i64 element
6563     // type.
6564     Scale = ByteShift ? Scale / 2 : Scale;
6565
6566     // We need to round trip through the appropriate type for the shift.
6567     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6568     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6569     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6570            "Illegal integer vector type");
6571     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6572
6573     V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6574     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6575   };
6576
6577   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6578   // keep doubling the size of the integer elements up to that. We can
6579   // then shift the elements of the integer vector by whole multiples of
6580   // their width within the elements of the larger integer vector. Test each
6581   // multiple to see if we can find a match with the moved element indices
6582   // and that the shifted in elements are all zeroable.
6583   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6584     for (int Shift = 1; Shift != Scale; ++Shift)
6585       for (bool Left : {true, false})
6586         if (CheckZeros(Shift, Scale, Left))
6587           for (SDValue V : {V1, V2})
6588             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6589               return Match;
6590
6591   // no match
6592   return SDValue();
6593 }
6594
6595 /// \brief Lower a vector shuffle as a zero or any extension.
6596 ///
6597 /// Given a specific number of elements, element bit width, and extension
6598 /// stride, produce either a zero or any extension based on the available
6599 /// features of the subtarget.
6600 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6601     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6602     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6603   assert(Scale > 1 && "Need a scale to extend.");
6604   int NumElements = VT.getVectorNumElements();
6605   int EltBits = VT.getScalarSizeInBits();
6606   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6607          "Only 8, 16, and 32 bit elements can be extended.");
6608   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6609
6610   // Found a valid zext mask! Try various lowering strategies based on the
6611   // input type and available ISA extensions.
6612   if (Subtarget->hasSSE41()) {
6613     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6614                                  NumElements / Scale);
6615     return DAG.getNode(ISD::BITCAST, DL, VT,
6616                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6617   }
6618
6619   // For any extends we can cheat for larger element sizes and use shuffle
6620   // instructions that can fold with a load and/or copy.
6621   if (AnyExt && EltBits == 32) {
6622     int PSHUFDMask[4] = {0, -1, 1, -1};
6623     return DAG.getNode(
6624         ISD::BITCAST, DL, VT,
6625         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6626                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6627                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6628   }
6629   if (AnyExt && EltBits == 16 && Scale > 2) {
6630     int PSHUFDMask[4] = {0, -1, 0, -1};
6631     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6632                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6633                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6634     int PSHUFHWMask[4] = {1, -1, -1, -1};
6635     return DAG.getNode(
6636         ISD::BITCAST, DL, VT,
6637         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6638                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6639                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6640   }
6641
6642   // If this would require more than 2 unpack instructions to expand, use
6643   // pshufb when available. We can only use more than 2 unpack instructions
6644   // when zero extending i8 elements which also makes it easier to use pshufb.
6645   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6646     assert(NumElements == 16 && "Unexpected byte vector width!");
6647     SDValue PSHUFBMask[16];
6648     for (int i = 0; i < 16; ++i)
6649       PSHUFBMask[i] =
6650           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6651     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6652     return DAG.getNode(ISD::BITCAST, DL, VT,
6653                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6654                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6655                                                MVT::v16i8, PSHUFBMask)));
6656   }
6657
6658   // Otherwise emit a sequence of unpacks.
6659   do {
6660     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6661     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6662                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6663     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6664     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6665     Scale /= 2;
6666     EltBits *= 2;
6667     NumElements /= 2;
6668   } while (Scale > 1);
6669   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6670 }
6671
6672 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6673 ///
6674 /// This routine will try to do everything in its power to cleverly lower
6675 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6676 /// check for the profitability of this lowering,  it tries to aggressively
6677 /// match this pattern. It will use all of the micro-architectural details it
6678 /// can to emit an efficient lowering. It handles both blends with all-zero
6679 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6680 /// masking out later).
6681 ///
6682 /// The reason we have dedicated lowering for zext-style shuffles is that they
6683 /// are both incredibly common and often quite performance sensitive.
6684 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6685     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6686     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6687   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6688
6689   int Bits = VT.getSizeInBits();
6690   int NumElements = VT.getVectorNumElements();
6691   assert(VT.getScalarSizeInBits() <= 32 &&
6692          "Exceeds 32-bit integer zero extension limit");
6693   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6694
6695   // Define a helper function to check a particular ext-scale and lower to it if
6696   // valid.
6697   auto Lower = [&](int Scale) -> SDValue {
6698     SDValue InputV;
6699     bool AnyExt = true;
6700     for (int i = 0; i < NumElements; ++i) {
6701       if (Mask[i] == -1)
6702         continue; // Valid anywhere but doesn't tell us anything.
6703       if (i % Scale != 0) {
6704         // Each of the extended elements need to be zeroable.
6705         if (!Zeroable[i])
6706           return SDValue();
6707
6708         // We no longer are in the anyext case.
6709         AnyExt = false;
6710         continue;
6711       }
6712
6713       // Each of the base elements needs to be consecutive indices into the
6714       // same input vector.
6715       SDValue V = Mask[i] < NumElements ? V1 : V2;
6716       if (!InputV)
6717         InputV = V;
6718       else if (InputV != V)
6719         return SDValue(); // Flip-flopping inputs.
6720
6721       if (Mask[i] % NumElements != i / Scale)
6722         return SDValue(); // Non-consecutive strided elements.
6723     }
6724
6725     // If we fail to find an input, we have a zero-shuffle which should always
6726     // have already been handled.
6727     // FIXME: Maybe handle this here in case during blending we end up with one?
6728     if (!InputV)
6729       return SDValue();
6730
6731     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6732         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6733   };
6734
6735   // The widest scale possible for extending is to a 64-bit integer.
6736   assert(Bits % 64 == 0 &&
6737          "The number of bits in a vector must be divisible by 64 on x86!");
6738   int NumExtElements = Bits / 64;
6739
6740   // Each iteration, try extending the elements half as much, but into twice as
6741   // many elements.
6742   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6743     assert(NumElements % NumExtElements == 0 &&
6744            "The input vector size must be divisible by the extended size.");
6745     if (SDValue V = Lower(NumElements / NumExtElements))
6746       return V;
6747   }
6748
6749   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6750   if (Bits != 128)
6751     return SDValue();
6752
6753   // Returns one of the source operands if the shuffle can be reduced to a
6754   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6755   auto CanZExtLowHalf = [&]() {
6756     for (int i = NumElements / 2; i != NumElements; ++i)
6757       if (!Zeroable[i])
6758         return SDValue();
6759     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6760       return V1;
6761     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6762       return V2;
6763     return SDValue();
6764   };
6765
6766   if (SDValue V = CanZExtLowHalf()) {
6767     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6768     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6769     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6770   }
6771
6772   // No viable ext lowering found.
6773   return SDValue();
6774 }
6775
6776 /// \brief Try to get a scalar value for a specific element of a vector.
6777 ///
6778 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6779 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6780                                               SelectionDAG &DAG) {
6781   MVT VT = V.getSimpleValueType();
6782   MVT EltVT = VT.getVectorElementType();
6783   while (V.getOpcode() == ISD::BITCAST)
6784     V = V.getOperand(0);
6785   // If the bitcasts shift the element size, we can't extract an equivalent
6786   // element from it.
6787   MVT NewVT = V.getSimpleValueType();
6788   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6789     return SDValue();
6790
6791   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6792       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6793     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6794
6795   return SDValue();
6796 }
6797
6798 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6799 ///
6800 /// This is particularly important because the set of instructions varies
6801 /// significantly based on whether the operand is a load or not.
6802 static bool isShuffleFoldableLoad(SDValue V) {
6803   while (V.getOpcode() == ISD::BITCAST)
6804     V = V.getOperand(0);
6805
6806   return ISD::isNON_EXTLoad(V.getNode());
6807 }
6808
6809 /// \brief Try to lower insertion of a single element into a zero vector.
6810 ///
6811 /// This is a common pattern that we have especially efficient patterns to lower
6812 /// across all subtarget feature sets.
6813 static SDValue lowerVectorShuffleAsElementInsertion(
6814     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6815     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6816   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6817   MVT ExtVT = VT;
6818   MVT EltVT = VT.getVectorElementType();
6819
6820   int V2Index = std::find_if(Mask.begin(), Mask.end(),
6821                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
6822                 Mask.begin();
6823   bool IsV1Zeroable = true;
6824   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6825     if (i != V2Index && !Zeroable[i]) {
6826       IsV1Zeroable = false;
6827       break;
6828     }
6829
6830   // Check for a single input from a SCALAR_TO_VECTOR node.
6831   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6832   // all the smarts here sunk into that routine. However, the current
6833   // lowering of BUILD_VECTOR makes that nearly impossible until the old
6834   // vector shuffle lowering is dead.
6835   if (SDValue V2S = getScalarValueForVectorElement(
6836           V2, Mask[V2Index] - Mask.size(), DAG)) {
6837     // We need to zext the scalar if it is smaller than an i32.
6838     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6839     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6840       // Using zext to expand a narrow element won't work for non-zero
6841       // insertions.
6842       if (!IsV1Zeroable)
6843         return SDValue();
6844
6845       // Zero-extend directly to i32.
6846       ExtVT = MVT::v4i32;
6847       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6848     }
6849     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6850   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6851              EltVT == MVT::i16) {
6852     // Either not inserting from the low element of the input or the input
6853     // element size is too small to use VZEXT_MOVL to clear the high bits.
6854     return SDValue();
6855   }
6856
6857   if (!IsV1Zeroable) {
6858     // If V1 can't be treated as a zero vector we have fewer options to lower
6859     // this. We can't support integer vectors or non-zero targets cheaply, and
6860     // the V1 elements can't be permuted in any way.
6861     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6862     if (!VT.isFloatingPoint() || V2Index != 0)
6863       return SDValue();
6864     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6865     V1Mask[V2Index] = -1;
6866     if (!isNoopShuffleMask(V1Mask))
6867       return SDValue();
6868     // This is essentially a special case blend operation, but if we have
6869     // general purpose blend operations, they are always faster. Bail and let
6870     // the rest of the lowering handle these as blends.
6871     if (Subtarget->hasSSE41())
6872       return SDValue();
6873
6874     // Otherwise, use MOVSD or MOVSS.
6875     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6876            "Only two types of floating point element types to handle!");
6877     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6878                        ExtVT, V1, V2);
6879   }
6880
6881   // This lowering only works for the low element with floating point vectors.
6882   if (VT.isFloatingPoint() && V2Index != 0)
6883     return SDValue();
6884
6885   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6886   if (ExtVT != VT)
6887     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6888
6889   if (V2Index != 0) {
6890     // If we have 4 or fewer lanes we can cheaply shuffle the element into
6891     // the desired position. Otherwise it is more efficient to do a vector
6892     // shift left. We know that we can do a vector shift left because all
6893     // the inputs are zero.
6894     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6895       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6896       V2Shuffle[V2Index] = 0;
6897       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6898     } else {
6899       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6900       V2 = DAG.getNode(
6901           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6902           DAG.getConstant(
6903               V2Index * EltVT.getSizeInBits()/8,
6904               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6905       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6906     }
6907   }
6908   return V2;
6909 }
6910
6911 /// \brief Try to lower broadcast of a single element.
6912 ///
6913 /// For convenience, this code also bundles all of the subtarget feature set
6914 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6915 /// a convenient way to factor it out.
6916 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
6917                                              ArrayRef<int> Mask,
6918                                              const X86Subtarget *Subtarget,
6919                                              SelectionDAG &DAG) {
6920   if (!Subtarget->hasAVX())
6921     return SDValue();
6922   if (VT.isInteger() && !Subtarget->hasAVX2())
6923     return SDValue();
6924
6925   // Check that the mask is a broadcast.
6926   int BroadcastIdx = -1;
6927   for (int M : Mask)
6928     if (M >= 0 && BroadcastIdx == -1)
6929       BroadcastIdx = M;
6930     else if (M >= 0 && M != BroadcastIdx)
6931       return SDValue();
6932
6933   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6934                                             "a sorted mask where the broadcast "
6935                                             "comes from V1.");
6936
6937   // Go up the chain of (vector) values to try and find a scalar load that
6938   // we can combine with the broadcast.
6939   for (;;) {
6940     switch (V.getOpcode()) {
6941     case ISD::CONCAT_VECTORS: {
6942       int OperandSize = Mask.size() / V.getNumOperands();
6943       V = V.getOperand(BroadcastIdx / OperandSize);
6944       BroadcastIdx %= OperandSize;
6945       continue;
6946     }
6947
6948     case ISD::INSERT_SUBVECTOR: {
6949       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
6950       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
6951       if (!ConstantIdx)
6952         break;
6953
6954       int BeginIdx = (int)ConstantIdx->getZExtValue();
6955       int EndIdx =
6956           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
6957       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
6958         BroadcastIdx -= BeginIdx;
6959         V = VInner;
6960       } else {
6961         V = VOuter;
6962       }
6963       continue;
6964     }
6965     }
6966     break;
6967   }
6968
6969   // Check if this is a broadcast of a scalar. We special case lowering
6970   // for scalars so that we can more effectively fold with loads.
6971   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6972       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
6973     V = V.getOperand(BroadcastIdx);
6974
6975     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
6976     // AVX2.
6977     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
6978       return SDValue();
6979   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
6980     // We can't broadcast from a vector register w/o AVX2, and we can only
6981     // broadcast from the zero-element of a vector register.
6982     return SDValue();
6983   }
6984
6985   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
6986 }
6987
6988 // Check for whether we can use INSERTPS to perform the shuffle. We only use
6989 // INSERTPS when the V1 elements are already in the correct locations
6990 // because otherwise we can just always use two SHUFPS instructions which
6991 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
6992 // perform INSERTPS if a single V1 element is out of place and all V2
6993 // elements are zeroable.
6994 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
6995                                             ArrayRef<int> Mask,
6996                                             SelectionDAG &DAG) {
6997   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
6998   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
6999   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7000   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7001
7002   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7003
7004   unsigned ZMask = 0;
7005   int V1DstIndex = -1;
7006   int V2DstIndex = -1;
7007   bool V1UsedInPlace = false;
7008
7009   for (int i = 0; i < 4; ++i) {
7010     // Synthesize a zero mask from the zeroable elements (includes undefs).
7011     if (Zeroable[i]) {
7012       ZMask |= 1 << i;
7013       continue;
7014     }
7015
7016     // Flag if we use any V1 inputs in place.
7017     if (i == Mask[i]) {
7018       V1UsedInPlace = true;
7019       continue;
7020     }
7021
7022     // We can only insert a single non-zeroable element.
7023     if (V1DstIndex != -1 || V2DstIndex != -1)
7024       return SDValue();
7025
7026     if (Mask[i] < 4) {
7027       // V1 input out of place for insertion.
7028       V1DstIndex = i;
7029     } else {
7030       // V2 input for insertion.
7031       V2DstIndex = i;
7032     }
7033   }
7034
7035   // Don't bother if we have no (non-zeroable) element for insertion.
7036   if (V1DstIndex == -1 && V2DstIndex == -1)
7037     return SDValue();
7038
7039   // Determine element insertion src/dst indices. The src index is from the
7040   // start of the inserted vector, not the start of the concatenated vector.
7041   unsigned V2SrcIndex = 0;
7042   if (V1DstIndex != -1) {
7043     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7044     // and don't use the original V2 at all.
7045     V2SrcIndex = Mask[V1DstIndex];
7046     V2DstIndex = V1DstIndex;
7047     V2 = V1;
7048   } else {
7049     V2SrcIndex = Mask[V2DstIndex] - 4;
7050   }
7051
7052   // If no V1 inputs are used in place, then the result is created only from
7053   // the zero mask and the V2 insertion - so remove V1 dependency.
7054   if (!V1UsedInPlace)
7055     V1 = DAG.getUNDEF(MVT::v4f32);
7056
7057   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7058   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7059
7060   // Insert the V2 element into the desired position.
7061   SDLoc DL(Op);
7062   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7063                      DAG.getConstant(InsertPSMask, MVT::i8));
7064 }
7065
7066 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7067 /// UNPCK instruction.
7068 ///
7069 /// This specifically targets cases where we end up with alternating between
7070 /// the two inputs, and so can permute them into something that feeds a single
7071 /// UNPCK instruction. Note that this routine only targets integer vectors
7072 /// because for floating point vectors we have a generalized SHUFPS lowering
7073 /// strategy that handles everything that doesn't *exactly* match an unpack,
7074 /// making this clever lowering unnecessary.
7075 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7076                                           SDValue V2, ArrayRef<int> Mask,
7077                                           SelectionDAG &DAG) {
7078   assert(!VT.isFloatingPoint() &&
7079          "This routine only supports integer vectors.");
7080   assert(!isSingleInputShuffleMask(Mask) &&
7081          "This routine should only be used when blending two inputs.");
7082   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7083
7084   int Size = Mask.size();
7085
7086   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7087     return M >= 0 && M % Size < Size / 2;
7088   });
7089   int NumHiInputs = std::count_if(
7090       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7091
7092   bool UnpackLo = NumLoInputs >= NumHiInputs;
7093
7094   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7095     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7096     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7097
7098     for (int i = 0; i < Size; ++i) {
7099       if (Mask[i] < 0)
7100         continue;
7101
7102       // Each element of the unpack contains Scale elements from this mask.
7103       int UnpackIdx = i / Scale;
7104
7105       // We only handle the case where V1 feeds the first slots of the unpack.
7106       // We rely on canonicalization to ensure this is the case.
7107       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7108         return SDValue();
7109
7110       // Setup the mask for this input. The indexing is tricky as we have to
7111       // handle the unpack stride.
7112       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7113       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7114           Mask[i] % Size;
7115     }
7116
7117     // If we will have to shuffle both inputs to use the unpack, check whether
7118     // we can just unpack first and shuffle the result. If so, skip this unpack.
7119     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7120         !isNoopShuffleMask(V2Mask))
7121       return SDValue();
7122
7123     // Shuffle the inputs into place.
7124     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7125     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7126
7127     // Cast the inputs to the type we will use to unpack them.
7128     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7129     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7130
7131     // Unpack the inputs and cast the result back to the desired type.
7132     return DAG.getNode(ISD::BITCAST, DL, VT,
7133                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7134                                    DL, UnpackVT, V1, V2));
7135   };
7136
7137   // We try each unpack from the largest to the smallest to try and find one
7138   // that fits this mask.
7139   int OrigNumElements = VT.getVectorNumElements();
7140   int OrigScalarSize = VT.getScalarSizeInBits();
7141   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7142     int Scale = ScalarSize / OrigScalarSize;
7143     int NumElements = OrigNumElements / Scale;
7144     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7145     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7146       return Unpack;
7147   }
7148
7149   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7150   // initial unpack.
7151   if (NumLoInputs == 0 || NumHiInputs == 0) {
7152     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7153            "We have to have *some* inputs!");
7154     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7155
7156     // FIXME: We could consider the total complexity of the permute of each
7157     // possible unpacking. Or at the least we should consider how many
7158     // half-crossings are created.
7159     // FIXME: We could consider commuting the unpacks.
7160
7161     SmallVector<int, 32> PermMask;
7162     PermMask.assign(Size, -1);
7163     for (int i = 0; i < Size; ++i) {
7164       if (Mask[i] < 0)
7165         continue;
7166
7167       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7168
7169       PermMask[i] =
7170           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7171     }
7172     return DAG.getVectorShuffle(
7173         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7174                             DL, VT, V1, V2),
7175         DAG.getUNDEF(VT), PermMask);
7176   }
7177
7178   return SDValue();
7179 }
7180
7181 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7182 ///
7183 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7184 /// support for floating point shuffles but not integer shuffles. These
7185 /// instructions will incur a domain crossing penalty on some chips though so
7186 /// it is better to avoid lowering through this for integer vectors where
7187 /// possible.
7188 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7189                                        const X86Subtarget *Subtarget,
7190                                        SelectionDAG &DAG) {
7191   SDLoc DL(Op);
7192   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7193   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7194   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7195   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7196   ArrayRef<int> Mask = SVOp->getMask();
7197   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7198
7199   if (isSingleInputShuffleMask(Mask)) {
7200     // Use low duplicate instructions for masks that match their pattern.
7201     if (Subtarget->hasSSE3())
7202       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7203         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7204
7205     // Straight shuffle of a single input vector. Simulate this by using the
7206     // single input as both of the "inputs" to this instruction..
7207     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7208
7209     if (Subtarget->hasAVX()) {
7210       // If we have AVX, we can use VPERMILPS which will allow folding a load
7211       // into the shuffle.
7212       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7213                          DAG.getConstant(SHUFPDMask, MVT::i8));
7214     }
7215
7216     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7217                        DAG.getConstant(SHUFPDMask, MVT::i8));
7218   }
7219   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7220   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7221
7222   // If we have a single input, insert that into V1 if we can do so cheaply.
7223   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7224     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7225             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7226       return Insertion;
7227     // Try inverting the insertion since for v2 masks it is easy to do and we
7228     // can't reliably sort the mask one way or the other.
7229     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7230                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7231     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7232             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7233       return Insertion;
7234   }
7235
7236   // Try to use one of the special instruction patterns to handle two common
7237   // blend patterns if a zero-blend above didn't work.
7238   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7239       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7240     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7241       // We can either use a special instruction to load over the low double or
7242       // to move just the low double.
7243       return DAG.getNode(
7244           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7245           DL, MVT::v2f64, V2,
7246           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7247
7248   if (Subtarget->hasSSE41())
7249     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7250                                                   Subtarget, DAG))
7251       return Blend;
7252
7253   // Use dedicated unpack instructions for masks that match their pattern.
7254   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7255     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7256   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7257     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7258
7259   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7260   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7261                      DAG.getConstant(SHUFPDMask, MVT::i8));
7262 }
7263
7264 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7265 ///
7266 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7267 /// the integer unit to minimize domain crossing penalties. However, for blends
7268 /// it falls back to the floating point shuffle operation with appropriate bit
7269 /// casting.
7270 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7271                                        const X86Subtarget *Subtarget,
7272                                        SelectionDAG &DAG) {
7273   SDLoc DL(Op);
7274   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7275   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7276   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7277   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7278   ArrayRef<int> Mask = SVOp->getMask();
7279   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7280
7281   if (isSingleInputShuffleMask(Mask)) {
7282     // Check for being able to broadcast a single element.
7283     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7284                                                           Mask, Subtarget, DAG))
7285       return Broadcast;
7286
7287     // Straight shuffle of a single input vector. For everything from SSE2
7288     // onward this has a single fast instruction with no scary immediates.
7289     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7290     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7291     int WidenedMask[4] = {
7292         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7293         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7294     return DAG.getNode(
7295         ISD::BITCAST, DL, MVT::v2i64,
7296         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7297                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7298   }
7299   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7300   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7301   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7302   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7303
7304   // If we have a blend of two PACKUS operations an the blend aligns with the
7305   // low and half halves, we can just merge the PACKUS operations. This is
7306   // particularly important as it lets us merge shuffles that this routine itself
7307   // creates.
7308   auto GetPackNode = [](SDValue V) {
7309     while (V.getOpcode() == ISD::BITCAST)
7310       V = V.getOperand(0);
7311
7312     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7313   };
7314   if (SDValue V1Pack = GetPackNode(V1))
7315     if (SDValue V2Pack = GetPackNode(V2))
7316       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7317                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7318                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7319                                                   : V1Pack.getOperand(1),
7320                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7321                                                   : V2Pack.getOperand(1)));
7322
7323   // Try to use shift instructions.
7324   if (SDValue Shift =
7325           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7326     return Shift;
7327
7328   // When loading a scalar and then shuffling it into a vector we can often do
7329   // the insertion cheaply.
7330   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7331           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7332     return Insertion;
7333   // Try inverting the insertion since for v2 masks it is easy to do and we
7334   // can't reliably sort the mask one way or the other.
7335   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7336   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7337           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7338     return Insertion;
7339
7340   // We have different paths for blend lowering, but they all must use the
7341   // *exact* same predicate.
7342   bool IsBlendSupported = Subtarget->hasSSE41();
7343   if (IsBlendSupported)
7344     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7345                                                   Subtarget, DAG))
7346       return Blend;
7347
7348   // Use dedicated unpack instructions for masks that match their pattern.
7349   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7350     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7351   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7352     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7353
7354   // Try to use byte rotation instructions.
7355   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7356   if (Subtarget->hasSSSE3())
7357     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7358             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7359       return Rotate;
7360
7361   // If we have direct support for blends, we should lower by decomposing into
7362   // a permute. That will be faster than the domain cross.
7363   if (IsBlendSupported)
7364     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7365                                                       Mask, DAG);
7366
7367   // We implement this with SHUFPD which is pretty lame because it will likely
7368   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7369   // However, all the alternatives are still more cycles and newer chips don't
7370   // have this problem. It would be really nice if x86 had better shuffles here.
7371   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7372   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7373   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7374                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7375 }
7376
7377 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7378 ///
7379 /// This is used to disable more specialized lowerings when the shufps lowering
7380 /// will happen to be efficient.
7381 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7382   // This routine only handles 128-bit shufps.
7383   assert(Mask.size() == 4 && "Unsupported mask size!");
7384
7385   // To lower with a single SHUFPS we need to have the low half and high half
7386   // each requiring a single input.
7387   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7388     return false;
7389   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7390     return false;
7391
7392   return true;
7393 }
7394
7395 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7396 ///
7397 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7398 /// It makes no assumptions about whether this is the *best* lowering, it simply
7399 /// uses it.
7400 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7401                                             ArrayRef<int> Mask, SDValue V1,
7402                                             SDValue V2, SelectionDAG &DAG) {
7403   SDValue LowV = V1, HighV = V2;
7404   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7405
7406   int NumV2Elements =
7407       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7408
7409   if (NumV2Elements == 1) {
7410     int V2Index =
7411         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7412         Mask.begin();
7413
7414     // Compute the index adjacent to V2Index and in the same half by toggling
7415     // the low bit.
7416     int V2AdjIndex = V2Index ^ 1;
7417
7418     if (Mask[V2AdjIndex] == -1) {
7419       // Handles all the cases where we have a single V2 element and an undef.
7420       // This will only ever happen in the high lanes because we commute the
7421       // vector otherwise.
7422       if (V2Index < 2)
7423         std::swap(LowV, HighV);
7424       NewMask[V2Index] -= 4;
7425     } else {
7426       // Handle the case where the V2 element ends up adjacent to a V1 element.
7427       // To make this work, blend them together as the first step.
7428       int V1Index = V2AdjIndex;
7429       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7430       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7431                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7432
7433       // Now proceed to reconstruct the final blend as we have the necessary
7434       // high or low half formed.
7435       if (V2Index < 2) {
7436         LowV = V2;
7437         HighV = V1;
7438       } else {
7439         HighV = V2;
7440       }
7441       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7442       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7443     }
7444   } else if (NumV2Elements == 2) {
7445     if (Mask[0] < 4 && Mask[1] < 4) {
7446       // Handle the easy case where we have V1 in the low lanes and V2 in the
7447       // high lanes.
7448       NewMask[2] -= 4;
7449       NewMask[3] -= 4;
7450     } else if (Mask[2] < 4 && Mask[3] < 4) {
7451       // We also handle the reversed case because this utility may get called
7452       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7453       // arrange things in the right direction.
7454       NewMask[0] -= 4;
7455       NewMask[1] -= 4;
7456       HighV = V1;
7457       LowV = V2;
7458     } else {
7459       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7460       // trying to place elements directly, just blend them and set up the final
7461       // shuffle to place them.
7462
7463       // The first two blend mask elements are for V1, the second two are for
7464       // V2.
7465       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7466                           Mask[2] < 4 ? Mask[2] : Mask[3],
7467                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7468                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7469       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7470                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7471
7472       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7473       // a blend.
7474       LowV = HighV = V1;
7475       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7476       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7477       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7478       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7479     }
7480   }
7481   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7482                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7483 }
7484
7485 /// \brief Lower 4-lane 32-bit floating point shuffles.
7486 ///
7487 /// Uses instructions exclusively from the floating point unit to minimize
7488 /// domain crossing penalties, as these are sufficient to implement all v4f32
7489 /// shuffles.
7490 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7491                                        const X86Subtarget *Subtarget,
7492                                        SelectionDAG &DAG) {
7493   SDLoc DL(Op);
7494   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7495   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7496   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7497   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7498   ArrayRef<int> Mask = SVOp->getMask();
7499   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7500
7501   int NumV2Elements =
7502       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7503
7504   if (NumV2Elements == 0) {
7505     // Check for being able to broadcast a single element.
7506     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7507                                                           Mask, Subtarget, DAG))
7508       return Broadcast;
7509
7510     // Use even/odd duplicate instructions for masks that match their pattern.
7511     if (Subtarget->hasSSE3()) {
7512       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7513         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7514       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7515         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7516     }
7517
7518     if (Subtarget->hasAVX()) {
7519       // If we have AVX, we can use VPERMILPS which will allow folding a load
7520       // into the shuffle.
7521       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7522                          getV4X86ShuffleImm8ForMask(Mask, DAG));
7523     }
7524
7525     // Otherwise, use a straight shuffle of a single input vector. We pass the
7526     // input vector to both operands to simulate this with a SHUFPS.
7527     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7528                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7529   }
7530
7531   // There are special ways we can lower some single-element blends. However, we
7532   // have custom ways we can lower more complex single-element blends below that
7533   // we defer to if both this and BLENDPS fail to match, so restrict this to
7534   // when the V2 input is targeting element 0 of the mask -- that is the fast
7535   // case here.
7536   if (NumV2Elements == 1 && Mask[0] >= 4)
7537     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7538                                                          Mask, Subtarget, DAG))
7539       return V;
7540
7541   if (Subtarget->hasSSE41()) {
7542     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7543                                                   Subtarget, DAG))
7544       return Blend;
7545
7546     // Use INSERTPS if we can complete the shuffle efficiently.
7547     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7548       return V;
7549
7550     if (!isSingleSHUFPSMask(Mask))
7551       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7552               DL, MVT::v4f32, V1, V2, Mask, DAG))
7553         return BlendPerm;
7554   }
7555
7556   // Use dedicated unpack instructions for masks that match their pattern.
7557   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7558     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7559   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7560     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7561   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7562     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7563   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7564     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7565
7566   // Otherwise fall back to a SHUFPS lowering strategy.
7567   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7568 }
7569
7570 /// \brief Lower 4-lane i32 vector shuffles.
7571 ///
7572 /// We try to handle these with integer-domain shuffles where we can, but for
7573 /// blends we use the floating point domain blend instructions.
7574 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7575                                        const X86Subtarget *Subtarget,
7576                                        SelectionDAG &DAG) {
7577   SDLoc DL(Op);
7578   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7579   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7580   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7581   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7582   ArrayRef<int> Mask = SVOp->getMask();
7583   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7584
7585   // Whenever we can lower this as a zext, that instruction is strictly faster
7586   // than any alternative. It also allows us to fold memory operands into the
7587   // shuffle in many cases.
7588   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7589                                                          Mask, Subtarget, DAG))
7590     return ZExt;
7591
7592   int NumV2Elements =
7593       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7594
7595   if (NumV2Elements == 0) {
7596     // Check for being able to broadcast a single element.
7597     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7598                                                           Mask, Subtarget, DAG))
7599       return Broadcast;
7600
7601     // Straight shuffle of a single input vector. For everything from SSE2
7602     // onward this has a single fast instruction with no scary immediates.
7603     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7604     // but we aren't actually going to use the UNPCK instruction because doing
7605     // so prevents folding a load into this instruction or making a copy.
7606     const int UnpackLoMask[] = {0, 0, 1, 1};
7607     const int UnpackHiMask[] = {2, 2, 3, 3};
7608     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7609       Mask = UnpackLoMask;
7610     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7611       Mask = UnpackHiMask;
7612
7613     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7614                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7615   }
7616
7617   // Try to use shift instructions.
7618   if (SDValue Shift =
7619           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7620     return Shift;
7621
7622   // There are special ways we can lower some single-element blends.
7623   if (NumV2Elements == 1)
7624     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7625                                                          Mask, Subtarget, DAG))
7626       return V;
7627
7628   // We have different paths for blend lowering, but they all must use the
7629   // *exact* same predicate.
7630   bool IsBlendSupported = Subtarget->hasSSE41();
7631   if (IsBlendSupported)
7632     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7633                                                   Subtarget, DAG))
7634       return Blend;
7635
7636   if (SDValue Masked =
7637           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7638     return Masked;
7639
7640   // Use dedicated unpack instructions for masks that match their pattern.
7641   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7642     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7643   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7644     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7645   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7646     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7647   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7648     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7649
7650   // Try to use byte rotation instructions.
7651   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7652   if (Subtarget->hasSSSE3())
7653     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7654             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7655       return Rotate;
7656
7657   // If we have direct support for blends, we should lower by decomposing into
7658   // a permute. That will be faster than the domain cross.
7659   if (IsBlendSupported)
7660     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7661                                                       Mask, DAG);
7662
7663   // Try to lower by permuting the inputs into an unpack instruction.
7664   if (SDValue Unpack =
7665           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7666     return Unpack;
7667
7668   // We implement this with SHUFPS because it can blend from two vectors.
7669   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7670   // up the inputs, bypassing domain shift penalties that we would encur if we
7671   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7672   // relevant.
7673   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7674                      DAG.getVectorShuffle(
7675                          MVT::v4f32, DL,
7676                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7677                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7678 }
7679
7680 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7681 /// shuffle lowering, and the most complex part.
7682 ///
7683 /// The lowering strategy is to try to form pairs of input lanes which are
7684 /// targeted at the same half of the final vector, and then use a dword shuffle
7685 /// to place them onto the right half, and finally unpack the paired lanes into
7686 /// their final position.
7687 ///
7688 /// The exact breakdown of how to form these dword pairs and align them on the
7689 /// correct sides is really tricky. See the comments within the function for
7690 /// more of the details.
7691 ///
7692 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7693 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7694 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7695 /// vector, form the analogous 128-bit 8-element Mask.
7696 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7697     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7698     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7699   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7700   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7701
7702   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7703   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7704   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7705
7706   SmallVector<int, 4> LoInputs;
7707   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7708                [](int M) { return M >= 0; });
7709   std::sort(LoInputs.begin(), LoInputs.end());
7710   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7711   SmallVector<int, 4> HiInputs;
7712   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7713                [](int M) { return M >= 0; });
7714   std::sort(HiInputs.begin(), HiInputs.end());
7715   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7716   int NumLToL =
7717       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7718   int NumHToL = LoInputs.size() - NumLToL;
7719   int NumLToH =
7720       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7721   int NumHToH = HiInputs.size() - NumLToH;
7722   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7723   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7724   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7725   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7726
7727   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7728   // such inputs we can swap two of the dwords across the half mark and end up
7729   // with <=2 inputs to each half in each half. Once there, we can fall through
7730   // to the generic code below. For example:
7731   //
7732   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7733   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7734   //
7735   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7736   // and an existing 2-into-2 on the other half. In this case we may have to
7737   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7738   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7739   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7740   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7741   // half than the one we target for fixing) will be fixed when we re-enter this
7742   // path. We will also combine away any sequence of PSHUFD instructions that
7743   // result into a single instruction. Here is an example of the tricky case:
7744   //
7745   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7746   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7747   //
7748   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7749   //
7750   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7751   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7752   //
7753   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7754   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7755   //
7756   // The result is fine to be handled by the generic logic.
7757   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7758                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7759                           int AOffset, int BOffset) {
7760     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7761            "Must call this with A having 3 or 1 inputs from the A half.");
7762     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7763            "Must call this with B having 1 or 3 inputs from the B half.");
7764     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7765            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7766
7767     // Compute the index of dword with only one word among the three inputs in
7768     // a half by taking the sum of the half with three inputs and subtracting
7769     // the sum of the actual three inputs. The difference is the remaining
7770     // slot.
7771     int ADWord, BDWord;
7772     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7773     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7774     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7775     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7776     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7777     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7778     int TripleNonInputIdx =
7779         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7780     TripleDWord = TripleNonInputIdx / 2;
7781
7782     // We use xor with one to compute the adjacent DWord to whichever one the
7783     // OneInput is in.
7784     OneInputDWord = (OneInput / 2) ^ 1;
7785
7786     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7787     // and BToA inputs. If there is also such a problem with the BToB and AToB
7788     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7789     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7790     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7791     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7792       // Compute how many inputs will be flipped by swapping these DWords. We
7793       // need
7794       // to balance this to ensure we don't form a 3-1 shuffle in the other
7795       // half.
7796       int NumFlippedAToBInputs =
7797           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7798           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7799       int NumFlippedBToBInputs =
7800           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7801           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7802       if ((NumFlippedAToBInputs == 1 &&
7803            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7804           (NumFlippedBToBInputs == 1 &&
7805            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7806         // We choose whether to fix the A half or B half based on whether that
7807         // half has zero flipped inputs. At zero, we may not be able to fix it
7808         // with that half. We also bias towards fixing the B half because that
7809         // will more commonly be the high half, and we have to bias one way.
7810         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7811                                                        ArrayRef<int> Inputs) {
7812           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7813           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7814                                          PinnedIdx ^ 1) != Inputs.end();
7815           // Determine whether the free index is in the flipped dword or the
7816           // unflipped dword based on where the pinned index is. We use this bit
7817           // in an xor to conditionally select the adjacent dword.
7818           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7819           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7820                                              FixFreeIdx) != Inputs.end();
7821           if (IsFixIdxInput == IsFixFreeIdxInput)
7822             FixFreeIdx += 1;
7823           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7824                                         FixFreeIdx) != Inputs.end();
7825           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7826                  "We need to be changing the number of flipped inputs!");
7827           int PSHUFHalfMask[] = {0, 1, 2, 3};
7828           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7829           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7830                           MVT::v8i16, V,
7831                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7832
7833           for (int &M : Mask)
7834             if (M != -1 && M == FixIdx)
7835               M = FixFreeIdx;
7836             else if (M != -1 && M == FixFreeIdx)
7837               M = FixIdx;
7838         };
7839         if (NumFlippedBToBInputs != 0) {
7840           int BPinnedIdx =
7841               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7842           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7843         } else {
7844           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7845           int APinnedIdx =
7846               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7847           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7848         }
7849       }
7850     }
7851
7852     int PSHUFDMask[] = {0, 1, 2, 3};
7853     PSHUFDMask[ADWord] = BDWord;
7854     PSHUFDMask[BDWord] = ADWord;
7855     V = DAG.getNode(ISD::BITCAST, DL, VT,
7856                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
7857                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
7858                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7859
7860     // Adjust the mask to match the new locations of A and B.
7861     for (int &M : Mask)
7862       if (M != -1 && M/2 == ADWord)
7863         M = 2 * BDWord + M % 2;
7864       else if (M != -1 && M/2 == BDWord)
7865         M = 2 * ADWord + M % 2;
7866
7867     // Recurse back into this routine to re-compute state now that this isn't
7868     // a 3 and 1 problem.
7869     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
7870                                                      DAG);
7871   };
7872   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7873     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7874   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7875     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7876
7877   // At this point there are at most two inputs to the low and high halves from
7878   // each half. That means the inputs can always be grouped into dwords and
7879   // those dwords can then be moved to the correct half with a dword shuffle.
7880   // We use at most one low and one high word shuffle to collect these paired
7881   // inputs into dwords, and finally a dword shuffle to place them.
7882   int PSHUFLMask[4] = {-1, -1, -1, -1};
7883   int PSHUFHMask[4] = {-1, -1, -1, -1};
7884   int PSHUFDMask[4] = {-1, -1, -1, -1};
7885
7886   // First fix the masks for all the inputs that are staying in their
7887   // original halves. This will then dictate the targets of the cross-half
7888   // shuffles.
7889   auto fixInPlaceInputs =
7890       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7891                     MutableArrayRef<int> SourceHalfMask,
7892                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7893     if (InPlaceInputs.empty())
7894       return;
7895     if (InPlaceInputs.size() == 1) {
7896       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7897           InPlaceInputs[0] - HalfOffset;
7898       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7899       return;
7900     }
7901     if (IncomingInputs.empty()) {
7902       // Just fix all of the in place inputs.
7903       for (int Input : InPlaceInputs) {
7904         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7905         PSHUFDMask[Input / 2] = Input / 2;
7906       }
7907       return;
7908     }
7909
7910     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7911     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7912         InPlaceInputs[0] - HalfOffset;
7913     // Put the second input next to the first so that they are packed into
7914     // a dword. We find the adjacent index by toggling the low bit.
7915     int AdjIndex = InPlaceInputs[0] ^ 1;
7916     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7917     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7918     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7919   };
7920   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7921   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7922
7923   // Now gather the cross-half inputs and place them into a free dword of
7924   // their target half.
7925   // FIXME: This operation could almost certainly be simplified dramatically to
7926   // look more like the 3-1 fixing operation.
7927   auto moveInputsToRightHalf = [&PSHUFDMask](
7928       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7929       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7930       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7931       int DestOffset) {
7932     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7933       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7934     };
7935     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7936                                                int Word) {
7937       int LowWord = Word & ~1;
7938       int HighWord = Word | 1;
7939       return isWordClobbered(SourceHalfMask, LowWord) ||
7940              isWordClobbered(SourceHalfMask, HighWord);
7941     };
7942
7943     if (IncomingInputs.empty())
7944       return;
7945
7946     if (ExistingInputs.empty()) {
7947       // Map any dwords with inputs from them into the right half.
7948       for (int Input : IncomingInputs) {
7949         // If the source half mask maps over the inputs, turn those into
7950         // swaps and use the swapped lane.
7951         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7952           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7953             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7954                 Input - SourceOffset;
7955             // We have to swap the uses in our half mask in one sweep.
7956             for (int &M : HalfMask)
7957               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7958                 M = Input;
7959               else if (M == Input)
7960                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7961           } else {
7962             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7963                        Input - SourceOffset &&
7964                    "Previous placement doesn't match!");
7965           }
7966           // Note that this correctly re-maps both when we do a swap and when
7967           // we observe the other side of the swap above. We rely on that to
7968           // avoid swapping the members of the input list directly.
7969           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7970         }
7971
7972         // Map the input's dword into the correct half.
7973         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7974           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7975         else
7976           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7977                      Input / 2 &&
7978                  "Previous placement doesn't match!");
7979       }
7980
7981       // And just directly shift any other-half mask elements to be same-half
7982       // as we will have mirrored the dword containing the element into the
7983       // same position within that half.
7984       for (int &M : HalfMask)
7985         if (M >= SourceOffset && M < SourceOffset + 4) {
7986           M = M - SourceOffset + DestOffset;
7987           assert(M >= 0 && "This should never wrap below zero!");
7988         }
7989       return;
7990     }
7991
7992     // Ensure we have the input in a viable dword of its current half. This
7993     // is particularly tricky because the original position may be clobbered
7994     // by inputs being moved and *staying* in that half.
7995     if (IncomingInputs.size() == 1) {
7996       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7997         int InputFixed = std::find(std::begin(SourceHalfMask),
7998                                    std::end(SourceHalfMask), -1) -
7999                          std::begin(SourceHalfMask) + SourceOffset;
8000         SourceHalfMask[InputFixed - SourceOffset] =
8001             IncomingInputs[0] - SourceOffset;
8002         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8003                      InputFixed);
8004         IncomingInputs[0] = InputFixed;
8005       }
8006     } else if (IncomingInputs.size() == 2) {
8007       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8008           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8009         // We have two non-adjacent or clobbered inputs we need to extract from
8010         // the source half. To do this, we need to map them into some adjacent
8011         // dword slot in the source mask.
8012         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8013                               IncomingInputs[1] - SourceOffset};
8014
8015         // If there is a free slot in the source half mask adjacent to one of
8016         // the inputs, place the other input in it. We use (Index XOR 1) to
8017         // compute an adjacent index.
8018         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8019             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8020           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8021           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8022           InputsFixed[1] = InputsFixed[0] ^ 1;
8023         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8024                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8025           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8026           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8027           InputsFixed[0] = InputsFixed[1] ^ 1;
8028         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8029                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8030           // The two inputs are in the same DWord but it is clobbered and the
8031           // adjacent DWord isn't used at all. Move both inputs to the free
8032           // slot.
8033           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8034           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8035           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8036           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8037         } else {
8038           // The only way we hit this point is if there is no clobbering
8039           // (because there are no off-half inputs to this half) and there is no
8040           // free slot adjacent to one of the inputs. In this case, we have to
8041           // swap an input with a non-input.
8042           for (int i = 0; i < 4; ++i)
8043             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8044                    "We can't handle any clobbers here!");
8045           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8046                  "Cannot have adjacent inputs here!");
8047
8048           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8049           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8050
8051           // We also have to update the final source mask in this case because
8052           // it may need to undo the above swap.
8053           for (int &M : FinalSourceHalfMask)
8054             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8055               M = InputsFixed[1] + SourceOffset;
8056             else if (M == InputsFixed[1] + SourceOffset)
8057               M = (InputsFixed[0] ^ 1) + SourceOffset;
8058
8059           InputsFixed[1] = InputsFixed[0] ^ 1;
8060         }
8061
8062         // Point everything at the fixed inputs.
8063         for (int &M : HalfMask)
8064           if (M == IncomingInputs[0])
8065             M = InputsFixed[0] + SourceOffset;
8066           else if (M == IncomingInputs[1])
8067             M = InputsFixed[1] + SourceOffset;
8068
8069         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8070         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8071       }
8072     } else {
8073       llvm_unreachable("Unhandled input size!");
8074     }
8075
8076     // Now hoist the DWord down to the right half.
8077     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8078     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8079     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8080     for (int &M : HalfMask)
8081       for (int Input : IncomingInputs)
8082         if (M == Input)
8083           M = FreeDWord * 2 + Input % 2;
8084   };
8085   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8086                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8087   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8088                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8089
8090   // Now enact all the shuffles we've computed to move the inputs into their
8091   // target half.
8092   if (!isNoopShuffleMask(PSHUFLMask))
8093     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8094                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8095   if (!isNoopShuffleMask(PSHUFHMask))
8096     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8097                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8098   if (!isNoopShuffleMask(PSHUFDMask))
8099     V = DAG.getNode(ISD::BITCAST, DL, VT,
8100                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8101                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8102                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8103
8104   // At this point, each half should contain all its inputs, and we can then
8105   // just shuffle them into their final position.
8106   assert(std::count_if(LoMask.begin(), LoMask.end(),
8107                        [](int M) { return M >= 4; }) == 0 &&
8108          "Failed to lift all the high half inputs to the low mask!");
8109   assert(std::count_if(HiMask.begin(), HiMask.end(),
8110                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8111          "Failed to lift all the low half inputs to the high mask!");
8112
8113   // Do a half shuffle for the low mask.
8114   if (!isNoopShuffleMask(LoMask))
8115     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8116                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8117
8118   // Do a half shuffle with the high mask after shifting its values down.
8119   for (int &M : HiMask)
8120     if (M >= 0)
8121       M -= 4;
8122   if (!isNoopShuffleMask(HiMask))
8123     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8124                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8125
8126   return V;
8127 }
8128
8129 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8130 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8131                                           SDValue V2, ArrayRef<int> Mask,
8132                                           SelectionDAG &DAG, bool &V1InUse,
8133                                           bool &V2InUse) {
8134   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8135   SDValue V1Mask[16];
8136   SDValue V2Mask[16];
8137   V1InUse = false;
8138   V2InUse = false;
8139
8140   int Size = Mask.size();
8141   int Scale = 16 / Size;
8142   for (int i = 0; i < 16; ++i) {
8143     if (Mask[i / Scale] == -1) {
8144       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8145     } else {
8146       const int ZeroMask = 0x80;
8147       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8148                                           : ZeroMask;
8149       int V2Idx = Mask[i / Scale] < Size
8150                       ? ZeroMask
8151                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8152       if (Zeroable[i / Scale])
8153         V1Idx = V2Idx = ZeroMask;
8154       V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8155       V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8156       V1InUse |= (ZeroMask != V1Idx);
8157       V2InUse |= (ZeroMask != V2Idx);
8158     }
8159   }
8160
8161   if (V1InUse)
8162     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8163                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8164                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8165   if (V2InUse)
8166     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8167                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8168                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8169
8170   // If we need shuffled inputs from both, blend the two.
8171   SDValue V;
8172   if (V1InUse && V2InUse)
8173     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8174   else
8175     V = V1InUse ? V1 : V2;
8176
8177   // Cast the result back to the correct type.
8178   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8179 }
8180
8181 /// \brief Generic lowering of 8-lane i16 shuffles.
8182 ///
8183 /// This handles both single-input shuffles and combined shuffle/blends with
8184 /// two inputs. The single input shuffles are immediately delegated to
8185 /// a dedicated lowering routine.
8186 ///
8187 /// The blends are lowered in one of three fundamental ways. If there are few
8188 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8189 /// of the input is significantly cheaper when lowered as an interleaving of
8190 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8191 /// halves of the inputs separately (making them have relatively few inputs)
8192 /// and then concatenate them.
8193 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8194                                        const X86Subtarget *Subtarget,
8195                                        SelectionDAG &DAG) {
8196   SDLoc DL(Op);
8197   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8198   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8199   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8200   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8201   ArrayRef<int> OrigMask = SVOp->getMask();
8202   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8203                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8204   MutableArrayRef<int> Mask(MaskStorage);
8205
8206   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8207
8208   // Whenever we can lower this as a zext, that instruction is strictly faster
8209   // than any alternative.
8210   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8211           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8212     return ZExt;
8213
8214   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8215   (void)isV1;
8216   auto isV2 = [](int M) { return M >= 8; };
8217
8218   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8219
8220   if (NumV2Inputs == 0) {
8221     // Check for being able to broadcast a single element.
8222     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8223                                                           Mask, Subtarget, DAG))
8224       return Broadcast;
8225
8226     // Try to use shift instructions.
8227     if (SDValue Shift =
8228             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8229       return Shift;
8230
8231     // Use dedicated unpack instructions for masks that match their pattern.
8232     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8233       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8234     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8235       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8236
8237     // Try to use byte rotation instructions.
8238     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8239                                                         Mask, Subtarget, DAG))
8240       return Rotate;
8241
8242     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8243                                                      Subtarget, DAG);
8244   }
8245
8246   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8247          "All single-input shuffles should be canonicalized to be V1-input "
8248          "shuffles.");
8249
8250   // Try to use shift instructions.
8251   if (SDValue Shift =
8252           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8253     return Shift;
8254
8255   // There are special ways we can lower some single-element blends.
8256   if (NumV2Inputs == 1)
8257     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8258                                                          Mask, Subtarget, DAG))
8259       return V;
8260
8261   // We have different paths for blend lowering, but they all must use the
8262   // *exact* same predicate.
8263   bool IsBlendSupported = Subtarget->hasSSE41();
8264   if (IsBlendSupported)
8265     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8266                                                   Subtarget, DAG))
8267       return Blend;
8268
8269   if (SDValue Masked =
8270           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8271     return Masked;
8272
8273   // Use dedicated unpack instructions for masks that match their pattern.
8274   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8275     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8276   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8277     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8278
8279   // Try to use byte rotation instructions.
8280   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8281           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8282     return Rotate;
8283
8284   if (SDValue BitBlend =
8285           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8286     return BitBlend;
8287
8288   if (SDValue Unpack =
8289           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8290     return Unpack;
8291
8292   // If we can't directly blend but can use PSHUFB, that will be better as it
8293   // can both shuffle and set up the inefficient blend.
8294   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8295     bool V1InUse, V2InUse;
8296     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8297                                       V1InUse, V2InUse);
8298   }
8299
8300   // We can always bit-blend if we have to so the fallback strategy is to
8301   // decompose into single-input permutes and blends.
8302   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8303                                                       Mask, DAG);
8304 }
8305
8306 /// \brief Check whether a compaction lowering can be done by dropping even
8307 /// elements and compute how many times even elements must be dropped.
8308 ///
8309 /// This handles shuffles which take every Nth element where N is a power of
8310 /// two. Example shuffle masks:
8311 ///
8312 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8313 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8314 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8315 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8316 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8317 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8318 ///
8319 /// Any of these lanes can of course be undef.
8320 ///
8321 /// This routine only supports N <= 3.
8322 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8323 /// for larger N.
8324 ///
8325 /// \returns N above, or the number of times even elements must be dropped if
8326 /// there is such a number. Otherwise returns zero.
8327 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8328   // Figure out whether we're looping over two inputs or just one.
8329   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8330
8331   // The modulus for the shuffle vector entries is based on whether this is
8332   // a single input or not.
8333   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8334   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8335          "We should only be called with masks with a power-of-2 size!");
8336
8337   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8338
8339   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8340   // and 2^3 simultaneously. This is because we may have ambiguity with
8341   // partially undef inputs.
8342   bool ViableForN[3] = {true, true, true};
8343
8344   for (int i = 0, e = Mask.size(); i < e; ++i) {
8345     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8346     // want.
8347     if (Mask[i] == -1)
8348       continue;
8349
8350     bool IsAnyViable = false;
8351     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8352       if (ViableForN[j]) {
8353         uint64_t N = j + 1;
8354
8355         // The shuffle mask must be equal to (i * 2^N) % M.
8356         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8357           IsAnyViable = true;
8358         else
8359           ViableForN[j] = false;
8360       }
8361     // Early exit if we exhaust the possible powers of two.
8362     if (!IsAnyViable)
8363       break;
8364   }
8365
8366   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8367     if (ViableForN[j])
8368       return j + 1;
8369
8370   // Return 0 as there is no viable power of two.
8371   return 0;
8372 }
8373
8374 /// \brief Generic lowering of v16i8 shuffles.
8375 ///
8376 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8377 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8378 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8379 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8380 /// back together.
8381 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8382                                        const X86Subtarget *Subtarget,
8383                                        SelectionDAG &DAG) {
8384   SDLoc DL(Op);
8385   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8386   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8387   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8389   ArrayRef<int> Mask = SVOp->getMask();
8390   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8391
8392   // Try to use shift instructions.
8393   if (SDValue Shift =
8394           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8395     return Shift;
8396
8397   // Try to use byte rotation instructions.
8398   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8399           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8400     return Rotate;
8401
8402   // Try to use a zext lowering.
8403   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8404           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8405     return ZExt;
8406
8407   int NumV2Elements =
8408       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8409
8410   // For single-input shuffles, there are some nicer lowering tricks we can use.
8411   if (NumV2Elements == 0) {
8412     // Check for being able to broadcast a single element.
8413     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8414                                                           Mask, Subtarget, DAG))
8415       return Broadcast;
8416
8417     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8418     // Notably, this handles splat and partial-splat shuffles more efficiently.
8419     // However, it only makes sense if the pre-duplication shuffle simplifies
8420     // things significantly. Currently, this means we need to be able to
8421     // express the pre-duplication shuffle as an i16 shuffle.
8422     //
8423     // FIXME: We should check for other patterns which can be widened into an
8424     // i16 shuffle as well.
8425     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8426       for (int i = 0; i < 16; i += 2)
8427         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8428           return false;
8429
8430       return true;
8431     };
8432     auto tryToWidenViaDuplication = [&]() -> SDValue {
8433       if (!canWidenViaDuplication(Mask))
8434         return SDValue();
8435       SmallVector<int, 4> LoInputs;
8436       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8437                    [](int M) { return M >= 0 && M < 8; });
8438       std::sort(LoInputs.begin(), LoInputs.end());
8439       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8440                      LoInputs.end());
8441       SmallVector<int, 4> HiInputs;
8442       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8443                    [](int M) { return M >= 8; });
8444       std::sort(HiInputs.begin(), HiInputs.end());
8445       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8446                      HiInputs.end());
8447
8448       bool TargetLo = LoInputs.size() >= HiInputs.size();
8449       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8450       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8451
8452       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8453       SmallDenseMap<int, int, 8> LaneMap;
8454       for (int I : InPlaceInputs) {
8455         PreDupI16Shuffle[I/2] = I/2;
8456         LaneMap[I] = I;
8457       }
8458       int j = TargetLo ? 0 : 4, je = j + 4;
8459       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8460         // Check if j is already a shuffle of this input. This happens when
8461         // there are two adjacent bytes after we move the low one.
8462         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8463           // If we haven't yet mapped the input, search for a slot into which
8464           // we can map it.
8465           while (j < je && PreDupI16Shuffle[j] != -1)
8466             ++j;
8467
8468           if (j == je)
8469             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8470             return SDValue();
8471
8472           // Map this input with the i16 shuffle.
8473           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8474         }
8475
8476         // Update the lane map based on the mapping we ended up with.
8477         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8478       }
8479       V1 = DAG.getNode(
8480           ISD::BITCAST, DL, MVT::v16i8,
8481           DAG.getVectorShuffle(MVT::v8i16, DL,
8482                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8483                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8484
8485       // Unpack the bytes to form the i16s that will be shuffled into place.
8486       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8487                        MVT::v16i8, V1, V1);
8488
8489       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8490       for (int i = 0; i < 16; ++i)
8491         if (Mask[i] != -1) {
8492           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8493           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8494           if (PostDupI16Shuffle[i / 2] == -1)
8495             PostDupI16Shuffle[i / 2] = MappedMask;
8496           else
8497             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8498                    "Conflicting entrties in the original shuffle!");
8499         }
8500       return DAG.getNode(
8501           ISD::BITCAST, DL, MVT::v16i8,
8502           DAG.getVectorShuffle(MVT::v8i16, DL,
8503                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8504                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8505     };
8506     if (SDValue V = tryToWidenViaDuplication())
8507       return V;
8508   }
8509
8510   // Use dedicated unpack instructions for masks that match their pattern.
8511   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8512                                          0, 16, 1, 17, 2, 18, 3, 19,
8513                                          // High half.
8514                                          4, 20, 5, 21, 6, 22, 7, 23}))
8515     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8516   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8517                                          8, 24, 9, 25, 10, 26, 11, 27,
8518                                          // High half.
8519                                          12, 28, 13, 29, 14, 30, 15, 31}))
8520     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8521
8522   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8523   // with PSHUFB. It is important to do this before we attempt to generate any
8524   // blends but after all of the single-input lowerings. If the single input
8525   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8526   // want to preserve that and we can DAG combine any longer sequences into
8527   // a PSHUFB in the end. But once we start blending from multiple inputs,
8528   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8529   // and there are *very* few patterns that would actually be faster than the
8530   // PSHUFB approach because of its ability to zero lanes.
8531   //
8532   // FIXME: The only exceptions to the above are blends which are exact
8533   // interleavings with direct instructions supporting them. We currently don't
8534   // handle those well here.
8535   if (Subtarget->hasSSSE3()) {
8536     bool V1InUse = false;
8537     bool V2InUse = false;
8538
8539     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8540                                                 DAG, V1InUse, V2InUse);
8541
8542     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8543     // do so. This avoids using them to handle blends-with-zero which is
8544     // important as a single pshufb is significantly faster for that.
8545     if (V1InUse && V2InUse) {
8546       if (Subtarget->hasSSE41())
8547         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8548                                                       Mask, Subtarget, DAG))
8549           return Blend;
8550
8551       // We can use an unpack to do the blending rather than an or in some
8552       // cases. Even though the or may be (very minorly) more efficient, we
8553       // preference this lowering because there are common cases where part of
8554       // the complexity of the shuffles goes away when we do the final blend as
8555       // an unpack.
8556       // FIXME: It might be worth trying to detect if the unpack-feeding
8557       // shuffles will both be pshufb, in which case we shouldn't bother with
8558       // this.
8559       if (SDValue Unpack =
8560               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8561         return Unpack;
8562     }
8563
8564     return PSHUFB;
8565   }
8566
8567   // There are special ways we can lower some single-element blends.
8568   if (NumV2Elements == 1)
8569     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8570                                                          Mask, Subtarget, DAG))
8571       return V;
8572
8573   if (SDValue BitBlend =
8574           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8575     return BitBlend;
8576
8577   // Check whether a compaction lowering can be done. This handles shuffles
8578   // which take every Nth element for some even N. See the helper function for
8579   // details.
8580   //
8581   // We special case these as they can be particularly efficiently handled with
8582   // the PACKUSB instruction on x86 and they show up in common patterns of
8583   // rearranging bytes to truncate wide elements.
8584   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8585     // NumEvenDrops is the power of two stride of the elements. Another way of
8586     // thinking about it is that we need to drop the even elements this many
8587     // times to get the original input.
8588     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8589
8590     // First we need to zero all the dropped bytes.
8591     assert(NumEvenDrops <= 3 &&
8592            "No support for dropping even elements more than 3 times.");
8593     // We use the mask type to pick which bytes are preserved based on how many
8594     // elements are dropped.
8595     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8596     SDValue ByteClearMask =
8597         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8598                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8599     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8600     if (!IsSingleInput)
8601       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8602
8603     // Now pack things back together.
8604     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8605     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8606     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8607     for (int i = 1; i < NumEvenDrops; ++i) {
8608       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8609       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8610     }
8611
8612     return Result;
8613   }
8614
8615   // Handle multi-input cases by blending single-input shuffles.
8616   if (NumV2Elements > 0)
8617     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8618                                                       Mask, DAG);
8619
8620   // The fallback path for single-input shuffles widens this into two v8i16
8621   // vectors with unpacks, shuffles those, and then pulls them back together
8622   // with a pack.
8623   SDValue V = V1;
8624
8625   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8626   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8627   for (int i = 0; i < 16; ++i)
8628     if (Mask[i] >= 0)
8629       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8630
8631   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8632
8633   SDValue VLoHalf, VHiHalf;
8634   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8635   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8636   // i16s.
8637   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8638                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8639       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8640                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8641     // Use a mask to drop the high bytes.
8642     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8643     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8644                      DAG.getConstant(0x00FF, MVT::v8i16));
8645
8646     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8647     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8648
8649     // Squash the masks to point directly into VLoHalf.
8650     for (int &M : LoBlendMask)
8651       if (M >= 0)
8652         M /= 2;
8653     for (int &M : HiBlendMask)
8654       if (M >= 0)
8655         M /= 2;
8656   } else {
8657     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8658     // VHiHalf so that we can blend them as i16s.
8659     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8660                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8661     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8662                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8663   }
8664
8665   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8666   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8667
8668   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8669 }
8670
8671 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8672 ///
8673 /// This routine breaks down the specific type of 128-bit shuffle and
8674 /// dispatches to the lowering routines accordingly.
8675 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8676                                         MVT VT, const X86Subtarget *Subtarget,
8677                                         SelectionDAG &DAG) {
8678   switch (VT.SimpleTy) {
8679   case MVT::v2i64:
8680     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8681   case MVT::v2f64:
8682     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8683   case MVT::v4i32:
8684     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8685   case MVT::v4f32:
8686     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8687   case MVT::v8i16:
8688     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8689   case MVT::v16i8:
8690     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8691
8692   default:
8693     llvm_unreachable("Unimplemented!");
8694   }
8695 }
8696
8697 /// \brief Helper function to test whether a shuffle mask could be
8698 /// simplified by widening the elements being shuffled.
8699 ///
8700 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8701 /// leaves it in an unspecified state.
8702 ///
8703 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8704 /// shuffle masks. The latter have the special property of a '-2' representing
8705 /// a zero-ed lane of a vector.
8706 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8707                                     SmallVectorImpl<int> &WidenedMask) {
8708   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8709     // If both elements are undef, its trivial.
8710     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8711       WidenedMask.push_back(SM_SentinelUndef);
8712       continue;
8713     }
8714
8715     // Check for an undef mask and a mask value properly aligned to fit with
8716     // a pair of values. If we find such a case, use the non-undef mask's value.
8717     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8718       WidenedMask.push_back(Mask[i + 1] / 2);
8719       continue;
8720     }
8721     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8722       WidenedMask.push_back(Mask[i] / 2);
8723       continue;
8724     }
8725
8726     // When zeroing, we need to spread the zeroing across both lanes to widen.
8727     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8728       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8729           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8730         WidenedMask.push_back(SM_SentinelZero);
8731         continue;
8732       }
8733       return false;
8734     }
8735
8736     // Finally check if the two mask values are adjacent and aligned with
8737     // a pair.
8738     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8739       WidenedMask.push_back(Mask[i] / 2);
8740       continue;
8741     }
8742
8743     // Otherwise we can't safely widen the elements used in this shuffle.
8744     return false;
8745   }
8746   assert(WidenedMask.size() == Mask.size() / 2 &&
8747          "Incorrect size of mask after widening the elements!");
8748
8749   return true;
8750 }
8751
8752 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8753 ///
8754 /// This routine just extracts two subvectors, shuffles them independently, and
8755 /// then concatenates them back together. This should work effectively with all
8756 /// AVX vector shuffle types.
8757 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8758                                           SDValue V2, ArrayRef<int> Mask,
8759                                           SelectionDAG &DAG) {
8760   assert(VT.getSizeInBits() >= 256 &&
8761          "Only for 256-bit or wider vector shuffles!");
8762   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8763   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8764
8765   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8766   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8767
8768   int NumElements = VT.getVectorNumElements();
8769   int SplitNumElements = NumElements / 2;
8770   MVT ScalarVT = VT.getScalarType();
8771   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8772
8773   // Rather than splitting build-vectors, just build two narrower build
8774   // vectors. This helps shuffling with splats and zeros.
8775   auto SplitVector = [&](SDValue V) {
8776     while (V.getOpcode() == ISD::BITCAST)
8777       V = V->getOperand(0);
8778
8779     MVT OrigVT = V.getSimpleValueType();
8780     int OrigNumElements = OrigVT.getVectorNumElements();
8781     int OrigSplitNumElements = OrigNumElements / 2;
8782     MVT OrigScalarVT = OrigVT.getScalarType();
8783     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8784
8785     SDValue LoV, HiV;
8786
8787     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8788     if (!BV) {
8789       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8790                         DAG.getIntPtrConstant(0));
8791       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8792                         DAG.getIntPtrConstant(OrigSplitNumElements));
8793     } else {
8794
8795       SmallVector<SDValue, 16> LoOps, HiOps;
8796       for (int i = 0; i < OrigSplitNumElements; ++i) {
8797         LoOps.push_back(BV->getOperand(i));
8798         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8799       }
8800       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8801       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8802     }
8803     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8804                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8805   };
8806
8807   SDValue LoV1, HiV1, LoV2, HiV2;
8808   std::tie(LoV1, HiV1) = SplitVector(V1);
8809   std::tie(LoV2, HiV2) = SplitVector(V2);
8810
8811   // Now create two 4-way blends of these half-width vectors.
8812   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8813     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8814     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8815     for (int i = 0; i < SplitNumElements; ++i) {
8816       int M = HalfMask[i];
8817       if (M >= NumElements) {
8818         if (M >= NumElements + SplitNumElements)
8819           UseHiV2 = true;
8820         else
8821           UseLoV2 = true;
8822         V2BlendMask.push_back(M - NumElements);
8823         V1BlendMask.push_back(-1);
8824         BlendMask.push_back(SplitNumElements + i);
8825       } else if (M >= 0) {
8826         if (M >= SplitNumElements)
8827           UseHiV1 = true;
8828         else
8829           UseLoV1 = true;
8830         V2BlendMask.push_back(-1);
8831         V1BlendMask.push_back(M);
8832         BlendMask.push_back(i);
8833       } else {
8834         V2BlendMask.push_back(-1);
8835         V1BlendMask.push_back(-1);
8836         BlendMask.push_back(-1);
8837       }
8838     }
8839
8840     // Because the lowering happens after all combining takes place, we need to
8841     // manually combine these blend masks as much as possible so that we create
8842     // a minimal number of high-level vector shuffle nodes.
8843
8844     // First try just blending the halves of V1 or V2.
8845     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8846       return DAG.getUNDEF(SplitVT);
8847     if (!UseLoV2 && !UseHiV2)
8848       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8849     if (!UseLoV1 && !UseHiV1)
8850       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8851
8852     SDValue V1Blend, V2Blend;
8853     if (UseLoV1 && UseHiV1) {
8854       V1Blend =
8855         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8856     } else {
8857       // We only use half of V1 so map the usage down into the final blend mask.
8858       V1Blend = UseLoV1 ? LoV1 : HiV1;
8859       for (int i = 0; i < SplitNumElements; ++i)
8860         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8861           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8862     }
8863     if (UseLoV2 && UseHiV2) {
8864       V2Blend =
8865         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8866     } else {
8867       // We only use half of V2 so map the usage down into the final blend mask.
8868       V2Blend = UseLoV2 ? LoV2 : HiV2;
8869       for (int i = 0; i < SplitNumElements; ++i)
8870         if (BlendMask[i] >= SplitNumElements)
8871           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8872     }
8873     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8874   };
8875   SDValue Lo = HalfBlend(LoMask);
8876   SDValue Hi = HalfBlend(HiMask);
8877   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8878 }
8879
8880 /// \brief Either split a vector in halves or decompose the shuffles and the
8881 /// blend.
8882 ///
8883 /// This is provided as a good fallback for many lowerings of non-single-input
8884 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8885 /// between splitting the shuffle into 128-bit components and stitching those
8886 /// back together vs. extracting the single-input shuffles and blending those
8887 /// results.
8888 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8889                                                 SDValue V2, ArrayRef<int> Mask,
8890                                                 SelectionDAG &DAG) {
8891   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8892                                             "lower single-input shuffles as it "
8893                                             "could then recurse on itself.");
8894   int Size = Mask.size();
8895
8896   // If this can be modeled as a broadcast of two elements followed by a blend,
8897   // prefer that lowering. This is especially important because broadcasts can
8898   // often fold with memory operands.
8899   auto DoBothBroadcast = [&] {
8900     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8901     for (int M : Mask)
8902       if (M >= Size) {
8903         if (V2BroadcastIdx == -1)
8904           V2BroadcastIdx = M - Size;
8905         else if (M - Size != V2BroadcastIdx)
8906           return false;
8907       } else if (M >= 0) {
8908         if (V1BroadcastIdx == -1)
8909           V1BroadcastIdx = M;
8910         else if (M != V1BroadcastIdx)
8911           return false;
8912       }
8913     return true;
8914   };
8915   if (DoBothBroadcast())
8916     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8917                                                       DAG);
8918
8919   // If the inputs all stem from a single 128-bit lane of each input, then we
8920   // split them rather than blending because the split will decompose to
8921   // unusually few instructions.
8922   int LaneCount = VT.getSizeInBits() / 128;
8923   int LaneSize = Size / LaneCount;
8924   SmallBitVector LaneInputs[2];
8925   LaneInputs[0].resize(LaneCount, false);
8926   LaneInputs[1].resize(LaneCount, false);
8927   for (int i = 0; i < Size; ++i)
8928     if (Mask[i] >= 0)
8929       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8930   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8931     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8932
8933   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8934   // that the decomposed single-input shuffles don't end up here.
8935   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8936 }
8937
8938 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
8939 /// a permutation and blend of those lanes.
8940 ///
8941 /// This essentially blends the out-of-lane inputs to each lane into the lane
8942 /// from a permuted copy of the vector. This lowering strategy results in four
8943 /// instructions in the worst case for a single-input cross lane shuffle which
8944 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
8945 /// of. Special cases for each particular shuffle pattern should be handled
8946 /// prior to trying this lowering.
8947 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
8948                                                        SDValue V1, SDValue V2,
8949                                                        ArrayRef<int> Mask,
8950                                                        SelectionDAG &DAG) {
8951   // FIXME: This should probably be generalized for 512-bit vectors as well.
8952   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8953   int LaneSize = Mask.size() / 2;
8954
8955   // If there are only inputs from one 128-bit lane, splitting will in fact be
8956   // less expensive. The flags track wether the given lane contains an element
8957   // that crosses to another lane.
8958   bool LaneCrossing[2] = {false, false};
8959   for (int i = 0, Size = Mask.size(); i < Size; ++i)
8960     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
8961       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
8962   if (!LaneCrossing[0] || !LaneCrossing[1])
8963     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8964
8965   if (isSingleInputShuffleMask(Mask)) {
8966     SmallVector<int, 32> FlippedBlendMask;
8967     for (int i = 0, Size = Mask.size(); i < Size; ++i)
8968       FlippedBlendMask.push_back(
8969           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
8970                                   ? Mask[i]
8971                                   : Mask[i] % LaneSize +
8972                                         (i / LaneSize) * LaneSize + Size));
8973
8974     // Flip the vector, and blend the results which should now be in-lane. The
8975     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
8976     // 5 for the high source. The value 3 selects the high half of source 2 and
8977     // the value 2 selects the low half of source 2. We only use source 2 to
8978     // allow folding it into a memory operand.
8979     unsigned PERMMask = 3 | 2 << 4;
8980     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
8981                                   V1, DAG.getConstant(PERMMask, MVT::i8));
8982     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
8983   }
8984
8985   // This now reduces to two single-input shuffles of V1 and V2 which at worst
8986   // will be handled by the above logic and a blend of the results, much like
8987   // other patterns in AVX.
8988   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8989 }
8990
8991 /// \brief Handle lowering 2-lane 128-bit shuffles.
8992 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8993                                         SDValue V2, ArrayRef<int> Mask,
8994                                         const X86Subtarget *Subtarget,
8995                                         SelectionDAG &DAG) {
8996   // Blends are faster and handle all the non-lane-crossing cases.
8997   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
8998                                                 Subtarget, DAG))
8999     return Blend;
9000
9001   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9002                                VT.getVectorNumElements() / 2);
9003   // Check for patterns which can be matched with a single insert of a 128-bit
9004   // subvector.
9005   if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}) ||
9006       isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9007     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9008                               DAG.getIntPtrConstant(0));
9009     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9010                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
9011     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9012   }
9013   if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 6, 7})) {
9014     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9015                               DAG.getIntPtrConstant(0));
9016     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9017                               DAG.getIntPtrConstant(2));
9018     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9019   }
9020
9021   // Otherwise form a 128-bit permutation.
9022   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9023   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
9024   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9025                      DAG.getConstant(PermMask, MVT::i8));
9026 }
9027
9028 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9029 /// shuffling each lane.
9030 ///
9031 /// This will only succeed when the result of fixing the 128-bit lanes results
9032 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9033 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9034 /// the lane crosses early and then use simpler shuffles within each lane.
9035 ///
9036 /// FIXME: It might be worthwhile at some point to support this without
9037 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9038 /// in x86 only floating point has interesting non-repeating shuffles, and even
9039 /// those are still *marginally* more expensive.
9040 static SDValue lowerVectorShuffleByMerging128BitLanes(
9041     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9042     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9043   assert(!isSingleInputShuffleMask(Mask) &&
9044          "This is only useful with multiple inputs.");
9045
9046   int Size = Mask.size();
9047   int LaneSize = 128 / VT.getScalarSizeInBits();
9048   int NumLanes = Size / LaneSize;
9049   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9050
9051   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9052   // check whether the in-128-bit lane shuffles share a repeating pattern.
9053   SmallVector<int, 4> Lanes;
9054   Lanes.resize(NumLanes, -1);
9055   SmallVector<int, 4> InLaneMask;
9056   InLaneMask.resize(LaneSize, -1);
9057   for (int i = 0; i < Size; ++i) {
9058     if (Mask[i] < 0)
9059       continue;
9060
9061     int j = i / LaneSize;
9062
9063     if (Lanes[j] < 0) {
9064       // First entry we've seen for this lane.
9065       Lanes[j] = Mask[i] / LaneSize;
9066     } else if (Lanes[j] != Mask[i] / LaneSize) {
9067       // This doesn't match the lane selected previously!
9068       return SDValue();
9069     }
9070
9071     // Check that within each lane we have a consistent shuffle mask.
9072     int k = i % LaneSize;
9073     if (InLaneMask[k] < 0) {
9074       InLaneMask[k] = Mask[i] % LaneSize;
9075     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9076       // This doesn't fit a repeating in-lane mask.
9077       return SDValue();
9078     }
9079   }
9080
9081   // First shuffle the lanes into place.
9082   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9083                                 VT.getSizeInBits() / 64);
9084   SmallVector<int, 8> LaneMask;
9085   LaneMask.resize(NumLanes * 2, -1);
9086   for (int i = 0; i < NumLanes; ++i)
9087     if (Lanes[i] >= 0) {
9088       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9089       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9090     }
9091
9092   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9093   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9094   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9095
9096   // Cast it back to the type we actually want.
9097   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9098
9099   // Now do a simple shuffle that isn't lane crossing.
9100   SmallVector<int, 8> NewMask;
9101   NewMask.resize(Size, -1);
9102   for (int i = 0; i < Size; ++i)
9103     if (Mask[i] >= 0)
9104       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9105   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9106          "Must not introduce lane crosses at this point!");
9107
9108   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9109 }
9110
9111 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9112 /// given mask.
9113 ///
9114 /// This returns true if the elements from a particular input are already in the
9115 /// slot required by the given mask and require no permutation.
9116 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9117   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9118   int Size = Mask.size();
9119   for (int i = 0; i < Size; ++i)
9120     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9121       return false;
9122
9123   return true;
9124 }
9125
9126 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9127 ///
9128 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9129 /// isn't available.
9130 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9131                                        const X86Subtarget *Subtarget,
9132                                        SelectionDAG &DAG) {
9133   SDLoc DL(Op);
9134   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9135   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9136   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9137   ArrayRef<int> Mask = SVOp->getMask();
9138   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9139
9140   SmallVector<int, 4> WidenedMask;
9141   if (canWidenShuffleElements(Mask, WidenedMask))
9142     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9143                                     DAG);
9144
9145   if (isSingleInputShuffleMask(Mask)) {
9146     // Check for being able to broadcast a single element.
9147     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9148                                                           Mask, Subtarget, DAG))
9149       return Broadcast;
9150
9151     // Use low duplicate instructions for masks that match their pattern.
9152     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9153       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9154
9155     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9156       // Non-half-crossing single input shuffles can be lowerid with an
9157       // interleaved permutation.
9158       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9159                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9160       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9161                          DAG.getConstant(VPERMILPMask, MVT::i8));
9162     }
9163
9164     // With AVX2 we have direct support for this permutation.
9165     if (Subtarget->hasAVX2())
9166       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9167                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9168
9169     // Otherwise, fall back.
9170     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9171                                                    DAG);
9172   }
9173
9174   // X86 has dedicated unpack instructions that can handle specific blend
9175   // operations: UNPCKH and UNPCKL.
9176   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9177     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9178   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9179     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9180   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9181     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9182   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9183     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9184
9185   // If we have a single input to the zero element, insert that into V1 if we
9186   // can do so cheaply.
9187   int NumV2Elements =
9188       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9189   if (NumV2Elements == 1 && Mask[0] >= 4)
9190     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9191             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9192       return Insertion;
9193
9194   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9195                                                 Subtarget, DAG))
9196     return Blend;
9197
9198   // Check if the blend happens to exactly fit that of SHUFPD.
9199   if ((Mask[0] == -1 || Mask[0] < 2) &&
9200       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9201       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9202       (Mask[3] == -1 || Mask[3] >= 6)) {
9203     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9204                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9205     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9206                        DAG.getConstant(SHUFPDMask, MVT::i8));
9207   }
9208   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9209       (Mask[1] == -1 || Mask[1] < 2) &&
9210       (Mask[2] == -1 || Mask[2] >= 6) &&
9211       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9212     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9213                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9214     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9215                        DAG.getConstant(SHUFPDMask, MVT::i8));
9216   }
9217
9218   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9219   // shuffle. However, if we have AVX2 and either inputs are already in place,
9220   // we will be able to shuffle even across lanes the other input in a single
9221   // instruction so skip this pattern.
9222   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9223                                  isShuffleMaskInputInPlace(1, Mask))))
9224     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9225             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9226       return Result;
9227
9228   // If we have AVX2 then we always want to lower with a blend because an v4 we
9229   // can fully permute the elements.
9230   if (Subtarget->hasAVX2())
9231     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9232                                                       Mask, DAG);
9233
9234   // Otherwise fall back on generic lowering.
9235   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9236 }
9237
9238 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9239 ///
9240 /// This routine is only called when we have AVX2 and thus a reasonable
9241 /// instruction set for v4i64 shuffling..
9242 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9243                                        const X86Subtarget *Subtarget,
9244                                        SelectionDAG &DAG) {
9245   SDLoc DL(Op);
9246   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9247   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9248   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9249   ArrayRef<int> Mask = SVOp->getMask();
9250   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9251   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9252
9253   SmallVector<int, 4> WidenedMask;
9254   if (canWidenShuffleElements(Mask, WidenedMask))
9255     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9256                                     DAG);
9257
9258   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9259                                                 Subtarget, DAG))
9260     return Blend;
9261
9262   // Check for being able to broadcast a single element.
9263   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9264                                                         Mask, Subtarget, DAG))
9265     return Broadcast;
9266
9267   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9268   // use lower latency instructions that will operate on both 128-bit lanes.
9269   SmallVector<int, 2> RepeatedMask;
9270   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9271     if (isSingleInputShuffleMask(Mask)) {
9272       int PSHUFDMask[] = {-1, -1, -1, -1};
9273       for (int i = 0; i < 2; ++i)
9274         if (RepeatedMask[i] >= 0) {
9275           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9276           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9277         }
9278       return DAG.getNode(
9279           ISD::BITCAST, DL, MVT::v4i64,
9280           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9281                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9282                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9283     }
9284   }
9285
9286   // AVX2 provides a direct instruction for permuting a single input across
9287   // lanes.
9288   if (isSingleInputShuffleMask(Mask))
9289     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9290                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9291
9292   // Try to use shift instructions.
9293   if (SDValue Shift =
9294           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9295     return Shift;
9296
9297   // Use dedicated unpack instructions for masks that match their pattern.
9298   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9299     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9300   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9301     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9302   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9303     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9304   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9305     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9306
9307   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9308   // shuffle. However, if we have AVX2 and either inputs are already in place,
9309   // we will be able to shuffle even across lanes the other input in a single
9310   // instruction so skip this pattern.
9311   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9312                                  isShuffleMaskInputInPlace(1, Mask))))
9313     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9314             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9315       return Result;
9316
9317   // Otherwise fall back on generic blend lowering.
9318   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9319                                                     Mask, DAG);
9320 }
9321
9322 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9323 ///
9324 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9325 /// isn't available.
9326 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9327                                        const X86Subtarget *Subtarget,
9328                                        SelectionDAG &DAG) {
9329   SDLoc DL(Op);
9330   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9331   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9332   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9333   ArrayRef<int> Mask = SVOp->getMask();
9334   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9335
9336   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9337                                                 Subtarget, DAG))
9338     return Blend;
9339
9340   // Check for being able to broadcast a single element.
9341   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9342                                                         Mask, Subtarget, DAG))
9343     return Broadcast;
9344
9345   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9346   // options to efficiently lower the shuffle.
9347   SmallVector<int, 4> RepeatedMask;
9348   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9349     assert(RepeatedMask.size() == 4 &&
9350            "Repeated masks must be half the mask width!");
9351
9352     // Use even/odd duplicate instructions for masks that match their pattern.
9353     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9354       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9355     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9356       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9357
9358     if (isSingleInputShuffleMask(Mask))
9359       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9360                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9361
9362     // Use dedicated unpack instructions for masks that match their pattern.
9363     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9364       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9365     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9366       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9367     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9368       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9369     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9370       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9371
9372     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9373     // have already handled any direct blends. We also need to squash the
9374     // repeated mask into a simulated v4f32 mask.
9375     for (int i = 0; i < 4; ++i)
9376       if (RepeatedMask[i] >= 8)
9377         RepeatedMask[i] -= 4;
9378     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9379   }
9380
9381   // If we have a single input shuffle with different shuffle patterns in the
9382   // two 128-bit lanes use the variable mask to VPERMILPS.
9383   if (isSingleInputShuffleMask(Mask)) {
9384     SDValue VPermMask[8];
9385     for (int i = 0; i < 8; ++i)
9386       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9387                                  : DAG.getConstant(Mask[i], MVT::i32);
9388     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9389       return DAG.getNode(
9390           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9391           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9392
9393     if (Subtarget->hasAVX2())
9394       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9395                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9396                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9397                                                  MVT::v8i32, VPermMask)),
9398                          V1);
9399
9400     // Otherwise, fall back.
9401     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9402                                                    DAG);
9403   }
9404
9405   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9406   // shuffle.
9407   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9408           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9409     return Result;
9410
9411   // If we have AVX2 then we always want to lower with a blend because at v8 we
9412   // can fully permute the elements.
9413   if (Subtarget->hasAVX2())
9414     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9415                                                       Mask, DAG);
9416
9417   // Otherwise fall back on generic lowering.
9418   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9419 }
9420
9421 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9422 ///
9423 /// This routine is only called when we have AVX2 and thus a reasonable
9424 /// instruction set for v8i32 shuffling..
9425 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9426                                        const X86Subtarget *Subtarget,
9427                                        SelectionDAG &DAG) {
9428   SDLoc DL(Op);
9429   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9430   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9431   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9432   ArrayRef<int> Mask = SVOp->getMask();
9433   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9434   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9435
9436   // Whenever we can lower this as a zext, that instruction is strictly faster
9437   // than any alternative. It also allows us to fold memory operands into the
9438   // shuffle in many cases.
9439   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9440                                                          Mask, Subtarget, DAG))
9441     return ZExt;
9442
9443   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9444                                                 Subtarget, DAG))
9445     return Blend;
9446
9447   // Check for being able to broadcast a single element.
9448   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9449                                                         Mask, Subtarget, DAG))
9450     return Broadcast;
9451
9452   // If the shuffle mask is repeated in each 128-bit lane we can use more
9453   // efficient instructions that mirror the shuffles across the two 128-bit
9454   // lanes.
9455   SmallVector<int, 4> RepeatedMask;
9456   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9457     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9458     if (isSingleInputShuffleMask(Mask))
9459       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9460                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9461
9462     // Use dedicated unpack instructions for masks that match their pattern.
9463     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9464       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9465     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9466       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9467     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9468       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9469     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9470       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9471   }
9472
9473   // Try to use shift instructions.
9474   if (SDValue Shift =
9475           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9476     return Shift;
9477
9478   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9479           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9480     return Rotate;
9481
9482   // If the shuffle patterns aren't repeated but it is a single input, directly
9483   // generate a cross-lane VPERMD instruction.
9484   if (isSingleInputShuffleMask(Mask)) {
9485     SDValue VPermMask[8];
9486     for (int i = 0; i < 8; ++i)
9487       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9488                                  : DAG.getConstant(Mask[i], MVT::i32);
9489     return DAG.getNode(
9490         X86ISD::VPERMV, DL, MVT::v8i32,
9491         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9492   }
9493
9494   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9495   // shuffle.
9496   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9497           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9498     return Result;
9499
9500   // Otherwise fall back on generic blend lowering.
9501   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9502                                                     Mask, DAG);
9503 }
9504
9505 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9506 ///
9507 /// This routine is only called when we have AVX2 and thus a reasonable
9508 /// instruction set for v16i16 shuffling..
9509 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9510                                         const X86Subtarget *Subtarget,
9511                                         SelectionDAG &DAG) {
9512   SDLoc DL(Op);
9513   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9514   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9515   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9516   ArrayRef<int> Mask = SVOp->getMask();
9517   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9518   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9519
9520   // Whenever we can lower this as a zext, that instruction is strictly faster
9521   // than any alternative. It also allows us to fold memory operands into the
9522   // shuffle in many cases.
9523   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9524                                                          Mask, Subtarget, DAG))
9525     return ZExt;
9526
9527   // Check for being able to broadcast a single element.
9528   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9529                                                         Mask, Subtarget, DAG))
9530     return Broadcast;
9531
9532   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9533                                                 Subtarget, DAG))
9534     return Blend;
9535
9536   // Use dedicated unpack instructions for masks that match their pattern.
9537   if (isShuffleEquivalent(V1, V2, Mask,
9538                           {// First 128-bit lane:
9539                            0, 16, 1, 17, 2, 18, 3, 19,
9540                            // Second 128-bit lane:
9541                            8, 24, 9, 25, 10, 26, 11, 27}))
9542     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9543   if (isShuffleEquivalent(V1, V2, Mask,
9544                           {// First 128-bit lane:
9545                            4, 20, 5, 21, 6, 22, 7, 23,
9546                            // Second 128-bit lane:
9547                            12, 28, 13, 29, 14, 30, 15, 31}))
9548     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9549
9550   // Try to use shift instructions.
9551   if (SDValue Shift =
9552           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9553     return Shift;
9554
9555   // Try to use byte rotation instructions.
9556   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9557           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9558     return Rotate;
9559
9560   if (isSingleInputShuffleMask(Mask)) {
9561     // There are no generalized cross-lane shuffle operations available on i16
9562     // element types.
9563     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9564       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9565                                                      Mask, DAG);
9566
9567     SmallVector<int, 8> RepeatedMask;
9568     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9569       // As this is a single-input shuffle, the repeated mask should be
9570       // a strictly valid v8i16 mask that we can pass through to the v8i16
9571       // lowering to handle even the v16 case.
9572       return lowerV8I16GeneralSingleInputVectorShuffle(
9573           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9574     }
9575
9576     SDValue PSHUFBMask[32];
9577     for (int i = 0; i < 16; ++i) {
9578       if (Mask[i] == -1) {
9579         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9580         continue;
9581       }
9582
9583       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9584       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9585       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9586       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9587     }
9588     return DAG.getNode(
9589         ISD::BITCAST, DL, MVT::v16i16,
9590         DAG.getNode(
9591             X86ISD::PSHUFB, DL, MVT::v32i8,
9592             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9593             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9594   }
9595
9596   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9597   // shuffle.
9598   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9599           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9600     return Result;
9601
9602   // Otherwise fall back on generic lowering.
9603   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9604 }
9605
9606 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9607 ///
9608 /// This routine is only called when we have AVX2 and thus a reasonable
9609 /// instruction set for v32i8 shuffling..
9610 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9611                                        const X86Subtarget *Subtarget,
9612                                        SelectionDAG &DAG) {
9613   SDLoc DL(Op);
9614   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9615   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9616   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9617   ArrayRef<int> Mask = SVOp->getMask();
9618   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9619   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9620
9621   // Whenever we can lower this as a zext, that instruction is strictly faster
9622   // than any alternative. It also allows us to fold memory operands into the
9623   // shuffle in many cases.
9624   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9625                                                          Mask, Subtarget, DAG))
9626     return ZExt;
9627
9628   // Check for being able to broadcast a single element.
9629   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9630                                                         Mask, Subtarget, DAG))
9631     return Broadcast;
9632
9633   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9634                                                 Subtarget, DAG))
9635     return Blend;
9636
9637   // Use dedicated unpack instructions for masks that match their pattern.
9638   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9639   // 256-bit lanes.
9640   if (isShuffleEquivalent(
9641           V1, V2, Mask,
9642           {// First 128-bit lane:
9643            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9644            // Second 128-bit lane:
9645            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9646     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9647   if (isShuffleEquivalent(
9648           V1, V2, Mask,
9649           {// First 128-bit lane:
9650            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9651            // Second 128-bit lane:
9652            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9653     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9654
9655   // Try to use shift instructions.
9656   if (SDValue Shift =
9657           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9658     return Shift;
9659
9660   // Try to use byte rotation instructions.
9661   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9662           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9663     return Rotate;
9664
9665   if (isSingleInputShuffleMask(Mask)) {
9666     // There are no generalized cross-lane shuffle operations available on i8
9667     // element types.
9668     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9669       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9670                                                      Mask, DAG);
9671
9672     SDValue PSHUFBMask[32];
9673     for (int i = 0; i < 32; ++i)
9674       PSHUFBMask[i] =
9675           Mask[i] < 0
9676               ? DAG.getUNDEF(MVT::i8)
9677               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9678
9679     return DAG.getNode(
9680         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9681         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9682   }
9683
9684   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9685   // shuffle.
9686   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9687           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9688     return Result;
9689
9690   // Otherwise fall back on generic lowering.
9691   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9692 }
9693
9694 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9695 ///
9696 /// This routine either breaks down the specific type of a 256-bit x86 vector
9697 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9698 /// together based on the available instructions.
9699 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9700                                         MVT VT, const X86Subtarget *Subtarget,
9701                                         SelectionDAG &DAG) {
9702   SDLoc DL(Op);
9703   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9704   ArrayRef<int> Mask = SVOp->getMask();
9705
9706   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9707   // check for those subtargets here and avoid much of the subtarget querying in
9708   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9709   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9710   // floating point types there eventually, just immediately cast everything to
9711   // a float and operate entirely in that domain.
9712   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9713     int ElementBits = VT.getScalarSizeInBits();
9714     if (ElementBits < 32)
9715       // No floating point type available, decompose into 128-bit vectors.
9716       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9717
9718     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9719                                 VT.getVectorNumElements());
9720     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9721     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9722     return DAG.getNode(ISD::BITCAST, DL, VT,
9723                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9724   }
9725
9726   switch (VT.SimpleTy) {
9727   case MVT::v4f64:
9728     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9729   case MVT::v4i64:
9730     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9731   case MVT::v8f32:
9732     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9733   case MVT::v8i32:
9734     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9735   case MVT::v16i16:
9736     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9737   case MVT::v32i8:
9738     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9739
9740   default:
9741     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9742   }
9743 }
9744
9745 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9746 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9747                                        const X86Subtarget *Subtarget,
9748                                        SelectionDAG &DAG) {
9749   SDLoc DL(Op);
9750   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9751   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9752   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9753   ArrayRef<int> Mask = SVOp->getMask();
9754   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9755
9756   // X86 has dedicated unpack instructions that can handle specific blend
9757   // operations: UNPCKH and UNPCKL.
9758   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9759     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9760   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9761     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9762
9763   // FIXME: Implement direct support for this type!
9764   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9765 }
9766
9767 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9768 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9769                                        const X86Subtarget *Subtarget,
9770                                        SelectionDAG &DAG) {
9771   SDLoc DL(Op);
9772   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9773   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9774   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9775   ArrayRef<int> Mask = SVOp->getMask();
9776   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9777
9778   // Use dedicated unpack instructions for masks that match their pattern.
9779   if (isShuffleEquivalent(V1, V2, Mask,
9780                           {// First 128-bit lane.
9781                            0, 16, 1, 17, 4, 20, 5, 21,
9782                            // Second 128-bit lane.
9783                            8, 24, 9, 25, 12, 28, 13, 29}))
9784     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9785   if (isShuffleEquivalent(V1, V2, Mask,
9786                           {// First 128-bit lane.
9787                            2, 18, 3, 19, 6, 22, 7, 23,
9788                            // Second 128-bit lane.
9789                            10, 26, 11, 27, 14, 30, 15, 31}))
9790     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9791
9792   // FIXME: Implement direct support for this type!
9793   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9794 }
9795
9796 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9797 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9798                                        const X86Subtarget *Subtarget,
9799                                        SelectionDAG &DAG) {
9800   SDLoc DL(Op);
9801   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9802   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9803   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9804   ArrayRef<int> Mask = SVOp->getMask();
9805   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9806
9807   // X86 has dedicated unpack instructions that can handle specific blend
9808   // operations: UNPCKH and UNPCKL.
9809   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9810     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9811   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9812     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9813
9814   // FIXME: Implement direct support for this type!
9815   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9816 }
9817
9818 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9819 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9820                                        const X86Subtarget *Subtarget,
9821                                        SelectionDAG &DAG) {
9822   SDLoc DL(Op);
9823   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9824   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9825   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9826   ArrayRef<int> Mask = SVOp->getMask();
9827   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9828
9829   // Use dedicated unpack instructions for masks that match their pattern.
9830   if (isShuffleEquivalent(V1, V2, Mask,
9831                           {// First 128-bit lane.
9832                            0, 16, 1, 17, 4, 20, 5, 21,
9833                            // Second 128-bit lane.
9834                            8, 24, 9, 25, 12, 28, 13, 29}))
9835     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9836   if (isShuffleEquivalent(V1, V2, Mask,
9837                           {// First 128-bit lane.
9838                            2, 18, 3, 19, 6, 22, 7, 23,
9839                            // Second 128-bit lane.
9840                            10, 26, 11, 27, 14, 30, 15, 31}))
9841     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9842
9843   // FIXME: Implement direct support for this type!
9844   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9845 }
9846
9847 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9848 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9849                                         const X86Subtarget *Subtarget,
9850                                         SelectionDAG &DAG) {
9851   SDLoc DL(Op);
9852   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9853   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9854   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9855   ArrayRef<int> Mask = SVOp->getMask();
9856   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9857   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9858
9859   // FIXME: Implement direct support for this type!
9860   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9861 }
9862
9863 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9864 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9865                                        const X86Subtarget *Subtarget,
9866                                        SelectionDAG &DAG) {
9867   SDLoc DL(Op);
9868   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9869   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9870   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9871   ArrayRef<int> Mask = SVOp->getMask();
9872   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9873   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9874
9875   // FIXME: Implement direct support for this type!
9876   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9877 }
9878
9879 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9880 ///
9881 /// This routine either breaks down the specific type of a 512-bit x86 vector
9882 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9883 /// together based on the available instructions.
9884 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9885                                         MVT VT, const X86Subtarget *Subtarget,
9886                                         SelectionDAG &DAG) {
9887   SDLoc DL(Op);
9888   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9889   ArrayRef<int> Mask = SVOp->getMask();
9890   assert(Subtarget->hasAVX512() &&
9891          "Cannot lower 512-bit vectors w/ basic ISA!");
9892
9893   // Check for being able to broadcast a single element.
9894   if (SDValue Broadcast =
9895           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
9896     return Broadcast;
9897
9898   // Dispatch to each element type for lowering. If we don't have supprot for
9899   // specific element type shuffles at 512 bits, immediately split them and
9900   // lower them. Each lowering routine of a given type is allowed to assume that
9901   // the requisite ISA extensions for that element type are available.
9902   switch (VT.SimpleTy) {
9903   case MVT::v8f64:
9904     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9905   case MVT::v16f32:
9906     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9907   case MVT::v8i64:
9908     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9909   case MVT::v16i32:
9910     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9911   case MVT::v32i16:
9912     if (Subtarget->hasBWI())
9913       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9914     break;
9915   case MVT::v64i8:
9916     if (Subtarget->hasBWI())
9917       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9918     break;
9919
9920   default:
9921     llvm_unreachable("Not a valid 512-bit x86 vector type!");
9922   }
9923
9924   // Otherwise fall back on splitting.
9925   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9926 }
9927
9928 /// \brief Top-level lowering for x86 vector shuffles.
9929 ///
9930 /// This handles decomposition, canonicalization, and lowering of all x86
9931 /// vector shuffles. Most of the specific lowering strategies are encapsulated
9932 /// above in helper routines. The canonicalization attempts to widen shuffles
9933 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
9934 /// s.t. only one of the two inputs needs to be tested, etc.
9935 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9936                                   SelectionDAG &DAG) {
9937   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9938   ArrayRef<int> Mask = SVOp->getMask();
9939   SDValue V1 = Op.getOperand(0);
9940   SDValue V2 = Op.getOperand(1);
9941   MVT VT = Op.getSimpleValueType();
9942   int NumElements = VT.getVectorNumElements();
9943   SDLoc dl(Op);
9944
9945   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9946
9947   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9948   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9949   if (V1IsUndef && V2IsUndef)
9950     return DAG.getUNDEF(VT);
9951
9952   // When we create a shuffle node we put the UNDEF node to second operand,
9953   // but in some cases the first operand may be transformed to UNDEF.
9954   // In this case we should just commute the node.
9955   if (V1IsUndef)
9956     return DAG.getCommutedVectorShuffle(*SVOp);
9957
9958   // Check for non-undef masks pointing at an undef vector and make the masks
9959   // undef as well. This makes it easier to match the shuffle based solely on
9960   // the mask.
9961   if (V2IsUndef)
9962     for (int M : Mask)
9963       if (M >= NumElements) {
9964         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
9965         for (int &M : NewMask)
9966           if (M >= NumElements)
9967             M = -1;
9968         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
9969       }
9970
9971   // We actually see shuffles that are entirely re-arrangements of a set of
9972   // zero inputs. This mostly happens while decomposing complex shuffles into
9973   // simple ones. Directly lower these as a buildvector of zeros.
9974   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9975   if (Zeroable.all())
9976     return getZeroVector(VT, Subtarget, DAG, dl);
9977
9978   // Try to collapse shuffles into using a vector type with fewer elements but
9979   // wider element types. We cap this to not form integers or floating point
9980   // elements wider than 64 bits, but it might be interesting to form i128
9981   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
9982   SmallVector<int, 16> WidenedMask;
9983   if (VT.getScalarSizeInBits() < 64 &&
9984       canWidenShuffleElements(Mask, WidenedMask)) {
9985     MVT NewEltVT = VT.isFloatingPoint()
9986                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
9987                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
9988     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
9989     // Make sure that the new vector type is legal. For example, v2f64 isn't
9990     // legal on SSE1.
9991     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
9992       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
9993       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
9994       return DAG.getNode(ISD::BITCAST, dl, VT,
9995                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
9996     }
9997   }
9998
9999   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10000   for (int M : SVOp->getMask())
10001     if (M < 0)
10002       ++NumUndefElements;
10003     else if (M < NumElements)
10004       ++NumV1Elements;
10005     else
10006       ++NumV2Elements;
10007
10008   // Commute the shuffle as needed such that more elements come from V1 than
10009   // V2. This allows us to match the shuffle pattern strictly on how many
10010   // elements come from V1 without handling the symmetric cases.
10011   if (NumV2Elements > NumV1Elements)
10012     return DAG.getCommutedVectorShuffle(*SVOp);
10013
10014   // When the number of V1 and V2 elements are the same, try to minimize the
10015   // number of uses of V2 in the low half of the vector. When that is tied,
10016   // ensure that the sum of indices for V1 is equal to or lower than the sum
10017   // indices for V2. When those are equal, try to ensure that the number of odd
10018   // indices for V1 is lower than the number of odd indices for V2.
10019   if (NumV1Elements == NumV2Elements) {
10020     int LowV1Elements = 0, LowV2Elements = 0;
10021     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10022       if (M >= NumElements)
10023         ++LowV2Elements;
10024       else if (M >= 0)
10025         ++LowV1Elements;
10026     if (LowV2Elements > LowV1Elements) {
10027       return DAG.getCommutedVectorShuffle(*SVOp);
10028     } else if (LowV2Elements == LowV1Elements) {
10029       int SumV1Indices = 0, SumV2Indices = 0;
10030       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10031         if (SVOp->getMask()[i] >= NumElements)
10032           SumV2Indices += i;
10033         else if (SVOp->getMask()[i] >= 0)
10034           SumV1Indices += i;
10035       if (SumV2Indices < SumV1Indices) {
10036         return DAG.getCommutedVectorShuffle(*SVOp);
10037       } else if (SumV2Indices == SumV1Indices) {
10038         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10039         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10040           if (SVOp->getMask()[i] >= NumElements)
10041             NumV2OddIndices += i % 2;
10042           else if (SVOp->getMask()[i] >= 0)
10043             NumV1OddIndices += i % 2;
10044         if (NumV2OddIndices < NumV1OddIndices)
10045           return DAG.getCommutedVectorShuffle(*SVOp);
10046       }
10047     }
10048   }
10049
10050   // For each vector width, delegate to a specialized lowering routine.
10051   if (VT.getSizeInBits() == 128)
10052     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10053
10054   if (VT.getSizeInBits() == 256)
10055     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10056
10057   // Force AVX-512 vectors to be scalarized for now.
10058   // FIXME: Implement AVX-512 support!
10059   if (VT.getSizeInBits() == 512)
10060     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10061
10062   llvm_unreachable("Unimplemented!");
10063 }
10064
10065 // This function assumes its argument is a BUILD_VECTOR of constants or
10066 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10067 // true.
10068 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10069                                     unsigned &MaskValue) {
10070   MaskValue = 0;
10071   unsigned NumElems = BuildVector->getNumOperands();
10072   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10073   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10074   unsigned NumElemsInLane = NumElems / NumLanes;
10075
10076   // Blend for v16i16 should be symetric for the both lanes.
10077   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10078     SDValue EltCond = BuildVector->getOperand(i);
10079     SDValue SndLaneEltCond =
10080         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10081
10082     int Lane1Cond = -1, Lane2Cond = -1;
10083     if (isa<ConstantSDNode>(EltCond))
10084       Lane1Cond = !isZero(EltCond);
10085     if (isa<ConstantSDNode>(SndLaneEltCond))
10086       Lane2Cond = !isZero(SndLaneEltCond);
10087
10088     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10089       // Lane1Cond != 0, means we want the first argument.
10090       // Lane1Cond == 0, means we want the second argument.
10091       // The encoding of this argument is 0 for the first argument, 1
10092       // for the second. Therefore, invert the condition.
10093       MaskValue |= !Lane1Cond << i;
10094     else if (Lane1Cond < 0)
10095       MaskValue |= !Lane2Cond << i;
10096     else
10097       return false;
10098   }
10099   return true;
10100 }
10101
10102 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10103 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10104                                            const X86Subtarget *Subtarget,
10105                                            SelectionDAG &DAG) {
10106   SDValue Cond = Op.getOperand(0);
10107   SDValue LHS = Op.getOperand(1);
10108   SDValue RHS = Op.getOperand(2);
10109   SDLoc dl(Op);
10110   MVT VT = Op.getSimpleValueType();
10111
10112   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10113     return SDValue();
10114   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10115
10116   // Only non-legal VSELECTs reach this lowering, convert those into generic
10117   // shuffles and re-use the shuffle lowering path for blends.
10118   SmallVector<int, 32> Mask;
10119   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10120     SDValue CondElt = CondBV->getOperand(i);
10121     Mask.push_back(
10122         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10123   }
10124   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10125 }
10126
10127 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10128   // A vselect where all conditions and data are constants can be optimized into
10129   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10130   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10131       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10132       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10133     return SDValue();
10134
10135   // Try to lower this to a blend-style vector shuffle. This can handle all
10136   // constant condition cases.
10137   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10138     return BlendOp;
10139
10140   // Variable blends are only legal from SSE4.1 onward.
10141   if (!Subtarget->hasSSE41())
10142     return SDValue();
10143
10144   // Only some types will be legal on some subtargets. If we can emit a legal
10145   // VSELECT-matching blend, return Op, and but if we need to expand, return
10146   // a null value.
10147   switch (Op.getSimpleValueType().SimpleTy) {
10148   default:
10149     // Most of the vector types have blends past SSE4.1.
10150     return Op;
10151
10152   case MVT::v32i8:
10153     // The byte blends for AVX vectors were introduced only in AVX2.
10154     if (Subtarget->hasAVX2())
10155       return Op;
10156
10157     return SDValue();
10158
10159   case MVT::v8i16:
10160   case MVT::v16i16:
10161     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10162     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10163       return Op;
10164
10165     // FIXME: We should custom lower this by fixing the condition and using i8
10166     // blends.
10167     return SDValue();
10168   }
10169 }
10170
10171 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10172   MVT VT = Op.getSimpleValueType();
10173   SDLoc dl(Op);
10174
10175   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10176     return SDValue();
10177
10178   if (VT.getSizeInBits() == 8) {
10179     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10180                                   Op.getOperand(0), Op.getOperand(1));
10181     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10182                                   DAG.getValueType(VT));
10183     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10184   }
10185
10186   if (VT.getSizeInBits() == 16) {
10187     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10188     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10189     if (Idx == 0)
10190       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10191                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10192                                      DAG.getNode(ISD::BITCAST, dl,
10193                                                  MVT::v4i32,
10194                                                  Op.getOperand(0)),
10195                                      Op.getOperand(1)));
10196     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10197                                   Op.getOperand(0), Op.getOperand(1));
10198     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10199                                   DAG.getValueType(VT));
10200     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10201   }
10202
10203   if (VT == MVT::f32) {
10204     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10205     // the result back to FR32 register. It's only worth matching if the
10206     // result has a single use which is a store or a bitcast to i32.  And in
10207     // the case of a store, it's not worth it if the index is a constant 0,
10208     // because a MOVSSmr can be used instead, which is smaller and faster.
10209     if (!Op.hasOneUse())
10210       return SDValue();
10211     SDNode *User = *Op.getNode()->use_begin();
10212     if ((User->getOpcode() != ISD::STORE ||
10213          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10214           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10215         (User->getOpcode() != ISD::BITCAST ||
10216          User->getValueType(0) != MVT::i32))
10217       return SDValue();
10218     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10219                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10220                                               Op.getOperand(0)),
10221                                               Op.getOperand(1));
10222     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10223   }
10224
10225   if (VT == MVT::i32 || VT == MVT::i64) {
10226     // ExtractPS/pextrq works with constant index.
10227     if (isa<ConstantSDNode>(Op.getOperand(1)))
10228       return Op;
10229   }
10230   return SDValue();
10231 }
10232
10233 /// Extract one bit from mask vector, like v16i1 or v8i1.
10234 /// AVX-512 feature.
10235 SDValue
10236 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10237   SDValue Vec = Op.getOperand(0);
10238   SDLoc dl(Vec);
10239   MVT VecVT = Vec.getSimpleValueType();
10240   SDValue Idx = Op.getOperand(1);
10241   MVT EltVT = Op.getSimpleValueType();
10242
10243   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10244   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10245          "Unexpected vector type in ExtractBitFromMaskVector");
10246
10247   // variable index can't be handled in mask registers,
10248   // extend vector to VR512
10249   if (!isa<ConstantSDNode>(Idx)) {
10250     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10251     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10252     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10253                               ExtVT.getVectorElementType(), Ext, Idx);
10254     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10255   }
10256
10257   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10258   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10259   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10260     rc = getRegClassFor(MVT::v16i1);
10261   unsigned MaxSift = rc->getSize()*8 - 1;
10262   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10263                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10264   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10265                     DAG.getConstant(MaxSift, MVT::i8));
10266   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10267                        DAG.getIntPtrConstant(0));
10268 }
10269
10270 SDValue
10271 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10272                                            SelectionDAG &DAG) const {
10273   SDLoc dl(Op);
10274   SDValue Vec = Op.getOperand(0);
10275   MVT VecVT = Vec.getSimpleValueType();
10276   SDValue Idx = Op.getOperand(1);
10277
10278   if (Op.getSimpleValueType() == MVT::i1)
10279     return ExtractBitFromMaskVector(Op, DAG);
10280
10281   if (!isa<ConstantSDNode>(Idx)) {
10282     if (VecVT.is512BitVector() ||
10283         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10284          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10285
10286       MVT MaskEltVT =
10287         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10288       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10289                                     MaskEltVT.getSizeInBits());
10290
10291       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10292       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10293                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10294                                 Idx, DAG.getConstant(0, getPointerTy()));
10295       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10296       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10297                         Perm, DAG.getConstant(0, getPointerTy()));
10298     }
10299     return SDValue();
10300   }
10301
10302   // If this is a 256-bit vector result, first extract the 128-bit vector and
10303   // then extract the element from the 128-bit vector.
10304   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10305
10306     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10307     // Get the 128-bit vector.
10308     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10309     MVT EltVT = VecVT.getVectorElementType();
10310
10311     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10312
10313     //if (IdxVal >= NumElems/2)
10314     //  IdxVal -= NumElems/2;
10315     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10316     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10317                        DAG.getConstant(IdxVal, MVT::i32));
10318   }
10319
10320   assert(VecVT.is128BitVector() && "Unexpected vector length");
10321
10322   if (Subtarget->hasSSE41()) {
10323     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10324     if (Res.getNode())
10325       return Res;
10326   }
10327
10328   MVT VT = Op.getSimpleValueType();
10329   // TODO: handle v16i8.
10330   if (VT.getSizeInBits() == 16) {
10331     SDValue Vec = Op.getOperand(0);
10332     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10333     if (Idx == 0)
10334       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10335                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10336                                      DAG.getNode(ISD::BITCAST, dl,
10337                                                  MVT::v4i32, Vec),
10338                                      Op.getOperand(1)));
10339     // Transform it so it match pextrw which produces a 32-bit result.
10340     MVT EltVT = MVT::i32;
10341     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10342                                   Op.getOperand(0), Op.getOperand(1));
10343     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10344                                   DAG.getValueType(VT));
10345     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10346   }
10347
10348   if (VT.getSizeInBits() == 32) {
10349     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10350     if (Idx == 0)
10351       return Op;
10352
10353     // SHUFPS the element to the lowest double word, then movss.
10354     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10355     MVT VVT = Op.getOperand(0).getSimpleValueType();
10356     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10357                                        DAG.getUNDEF(VVT), Mask);
10358     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10359                        DAG.getIntPtrConstant(0));
10360   }
10361
10362   if (VT.getSizeInBits() == 64) {
10363     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10364     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10365     //        to match extract_elt for f64.
10366     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10367     if (Idx == 0)
10368       return Op;
10369
10370     // UNPCKHPD the element to the lowest double word, then movsd.
10371     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10372     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10373     int Mask[2] = { 1, -1 };
10374     MVT VVT = Op.getOperand(0).getSimpleValueType();
10375     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10376                                        DAG.getUNDEF(VVT), Mask);
10377     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10378                        DAG.getIntPtrConstant(0));
10379   }
10380
10381   return SDValue();
10382 }
10383
10384 /// Insert one bit to mask vector, like v16i1 or v8i1.
10385 /// AVX-512 feature.
10386 SDValue
10387 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10388   SDLoc dl(Op);
10389   SDValue Vec = Op.getOperand(0);
10390   SDValue Elt = Op.getOperand(1);
10391   SDValue Idx = Op.getOperand(2);
10392   MVT VecVT = Vec.getSimpleValueType();
10393
10394   if (!isa<ConstantSDNode>(Idx)) {
10395     // Non constant index. Extend source and destination,
10396     // insert element and then truncate the result.
10397     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10398     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10399     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10400       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10401       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10402     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10403   }
10404
10405   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10406   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10407   if (Vec.getOpcode() == ISD::UNDEF)
10408     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10409                        DAG.getConstant(IdxVal, MVT::i8));
10410   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10411   unsigned MaxSift = rc->getSize()*8 - 1;
10412   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10413                     DAG.getConstant(MaxSift, MVT::i8));
10414   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10415                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10416   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10417 }
10418
10419 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10420                                                   SelectionDAG &DAG) const {
10421   MVT VT = Op.getSimpleValueType();
10422   MVT EltVT = VT.getVectorElementType();
10423
10424   if (EltVT == MVT::i1)
10425     return InsertBitToMaskVector(Op, DAG);
10426
10427   SDLoc dl(Op);
10428   SDValue N0 = Op.getOperand(0);
10429   SDValue N1 = Op.getOperand(1);
10430   SDValue N2 = Op.getOperand(2);
10431   if (!isa<ConstantSDNode>(N2))
10432     return SDValue();
10433   auto *N2C = cast<ConstantSDNode>(N2);
10434   unsigned IdxVal = N2C->getZExtValue();
10435
10436   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10437   // into that, and then insert the subvector back into the result.
10438   if (VT.is256BitVector() || VT.is512BitVector()) {
10439     // Get the desired 128-bit vector half.
10440     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10441
10442     // Insert the element into the desired half.
10443     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10444     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10445
10446     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10447                     DAG.getConstant(IdxIn128, MVT::i32));
10448
10449     // Insert the changed part back to the 256-bit vector
10450     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10451   }
10452   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10453
10454   if (Subtarget->hasSSE41()) {
10455     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10456       unsigned Opc;
10457       if (VT == MVT::v8i16) {
10458         Opc = X86ISD::PINSRW;
10459       } else {
10460         assert(VT == MVT::v16i8);
10461         Opc = X86ISD::PINSRB;
10462       }
10463
10464       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10465       // argument.
10466       if (N1.getValueType() != MVT::i32)
10467         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10468       if (N2.getValueType() != MVT::i32)
10469         N2 = DAG.getIntPtrConstant(IdxVal);
10470       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10471     }
10472
10473     if (EltVT == MVT::f32) {
10474       // Bits [7:6] of the constant are the source select.  This will always be
10475       //  zero here.  The DAG Combiner may combine an extract_elt index into
10476       //  these
10477       //  bits.  For example (insert (extract, 3), 2) could be matched by
10478       //  putting
10479       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10480       // Bits [5:4] of the constant are the destination select.  This is the
10481       //  value of the incoming immediate.
10482       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10483       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10484       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10485       // Create this as a scalar to vector..
10486       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10487       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10488     }
10489
10490     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10491       // PINSR* works with constant index.
10492       return Op;
10493     }
10494   }
10495
10496   if (EltVT == MVT::i8)
10497     return SDValue();
10498
10499   if (EltVT.getSizeInBits() == 16) {
10500     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10501     // as its second 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(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10507   }
10508   return SDValue();
10509 }
10510
10511 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10512   SDLoc dl(Op);
10513   MVT OpVT = Op.getSimpleValueType();
10514
10515   // If this is a 256-bit vector result, first insert into a 128-bit
10516   // vector and then insert into the 256-bit vector.
10517   if (!OpVT.is128BitVector()) {
10518     // Insert into a 128-bit vector.
10519     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10520     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10521                                  OpVT.getVectorNumElements() / SizeFactor);
10522
10523     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10524
10525     // Insert the 128-bit vector.
10526     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10527   }
10528
10529   if (OpVT == MVT::v1i64 &&
10530       Op.getOperand(0).getValueType() == MVT::i64)
10531     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10532
10533   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10534   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10535   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10536                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10537 }
10538
10539 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10540 // a simple subregister reference or explicit instructions to grab
10541 // upper bits of a vector.
10542 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10543                                       SelectionDAG &DAG) {
10544   SDLoc dl(Op);
10545   SDValue In =  Op.getOperand(0);
10546   SDValue Idx = Op.getOperand(1);
10547   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10548   MVT ResVT   = Op.getSimpleValueType();
10549   MVT InVT    = In.getSimpleValueType();
10550
10551   if (Subtarget->hasFp256()) {
10552     if (ResVT.is128BitVector() &&
10553         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10554         isa<ConstantSDNode>(Idx)) {
10555       return Extract128BitVector(In, IdxVal, DAG, dl);
10556     }
10557     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10558         isa<ConstantSDNode>(Idx)) {
10559       return Extract256BitVector(In, IdxVal, DAG, dl);
10560     }
10561   }
10562   return SDValue();
10563 }
10564
10565 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10566 // simple superregister reference or explicit instructions to insert
10567 // the upper bits of a vector.
10568 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10569                                      SelectionDAG &DAG) {
10570   if (!Subtarget->hasAVX())
10571     return SDValue();
10572
10573   SDLoc dl(Op);
10574   SDValue Vec = Op.getOperand(0);
10575   SDValue SubVec = Op.getOperand(1);
10576   SDValue Idx = Op.getOperand(2);
10577
10578   if (!isa<ConstantSDNode>(Idx))
10579     return SDValue();
10580
10581   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10582   MVT OpVT = Op.getSimpleValueType();
10583   MVT SubVecVT = SubVec.getSimpleValueType();
10584
10585   // Fold two 16-byte subvector loads into one 32-byte load:
10586   // (insert_subvector (insert_subvector undef, (load addr), 0),
10587   //                   (load addr + 16), Elts/2)
10588   // --> load32 addr
10589   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10590       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10591       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10592       !Subtarget->isUnalignedMem32Slow()) {
10593     SDValue SubVec2 = Vec.getOperand(1);
10594     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10595       if (Idx2->getZExtValue() == 0) {
10596         SDValue Ops[] = { SubVec2, SubVec };
10597         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10598         if (LD.getNode())
10599           return LD;
10600       }
10601     }
10602   }
10603
10604   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10605       SubVecVT.is128BitVector())
10606     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10607
10608   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10609     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10610
10611   return SDValue();
10612 }
10613
10614 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10615 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10616 // one of the above mentioned nodes. It has to be wrapped because otherwise
10617 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10618 // be used to form addressing mode. These wrapped nodes will be selected
10619 // into MOV32ri.
10620 SDValue
10621 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10622   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10623
10624   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10625   // global base reg.
10626   unsigned char OpFlag = 0;
10627   unsigned WrapperKind = X86ISD::Wrapper;
10628   CodeModel::Model M = DAG.getTarget().getCodeModel();
10629
10630   if (Subtarget->isPICStyleRIPRel() &&
10631       (M == CodeModel::Small || M == CodeModel::Kernel))
10632     WrapperKind = X86ISD::WrapperRIP;
10633   else if (Subtarget->isPICStyleGOT())
10634     OpFlag = X86II::MO_GOTOFF;
10635   else if (Subtarget->isPICStyleStubPIC())
10636     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10637
10638   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10639                                              CP->getAlignment(),
10640                                              CP->getOffset(), OpFlag);
10641   SDLoc DL(CP);
10642   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10643   // With PIC, the address is actually $g + Offset.
10644   if (OpFlag) {
10645     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10646                          DAG.getNode(X86ISD::GlobalBaseReg,
10647                                      SDLoc(), getPointerTy()),
10648                          Result);
10649   }
10650
10651   return Result;
10652 }
10653
10654 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10655   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10656
10657   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10658   // global base reg.
10659   unsigned char OpFlag = 0;
10660   unsigned WrapperKind = X86ISD::Wrapper;
10661   CodeModel::Model M = DAG.getTarget().getCodeModel();
10662
10663   if (Subtarget->isPICStyleRIPRel() &&
10664       (M == CodeModel::Small || M == CodeModel::Kernel))
10665     WrapperKind = X86ISD::WrapperRIP;
10666   else if (Subtarget->isPICStyleGOT())
10667     OpFlag = X86II::MO_GOTOFF;
10668   else if (Subtarget->isPICStyleStubPIC())
10669     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10670
10671   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10672                                           OpFlag);
10673   SDLoc DL(JT);
10674   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10675
10676   // With PIC, the address is actually $g + Offset.
10677   if (OpFlag)
10678     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10679                          DAG.getNode(X86ISD::GlobalBaseReg,
10680                                      SDLoc(), getPointerTy()),
10681                          Result);
10682
10683   return Result;
10684 }
10685
10686 SDValue
10687 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10688   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10689
10690   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10691   // global base reg.
10692   unsigned char OpFlag = 0;
10693   unsigned WrapperKind = X86ISD::Wrapper;
10694   CodeModel::Model M = DAG.getTarget().getCodeModel();
10695
10696   if (Subtarget->isPICStyleRIPRel() &&
10697       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10698     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10699       OpFlag = X86II::MO_GOTPCREL;
10700     WrapperKind = X86ISD::WrapperRIP;
10701   } else if (Subtarget->isPICStyleGOT()) {
10702     OpFlag = X86II::MO_GOT;
10703   } else if (Subtarget->isPICStyleStubPIC()) {
10704     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10705   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10706     OpFlag = X86II::MO_DARWIN_NONLAZY;
10707   }
10708
10709   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10710
10711   SDLoc DL(Op);
10712   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10713
10714   // With PIC, the address is actually $g + Offset.
10715   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10716       !Subtarget->is64Bit()) {
10717     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10718                          DAG.getNode(X86ISD::GlobalBaseReg,
10719                                      SDLoc(), getPointerTy()),
10720                          Result);
10721   }
10722
10723   // For symbols that require a load from a stub to get the address, emit the
10724   // load.
10725   if (isGlobalStubReference(OpFlag))
10726     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10727                          MachinePointerInfo::getGOT(), false, false, false, 0);
10728
10729   return Result;
10730 }
10731
10732 SDValue
10733 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10734   // Create the TargetBlockAddressAddress node.
10735   unsigned char OpFlags =
10736     Subtarget->ClassifyBlockAddressReference();
10737   CodeModel::Model M = DAG.getTarget().getCodeModel();
10738   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10739   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10740   SDLoc dl(Op);
10741   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10742                                              OpFlags);
10743
10744   if (Subtarget->isPICStyleRIPRel() &&
10745       (M == CodeModel::Small || M == CodeModel::Kernel))
10746     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10747   else
10748     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10749
10750   // With PIC, the address is actually $g + Offset.
10751   if (isGlobalRelativeToPICBase(OpFlags)) {
10752     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10753                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10754                          Result);
10755   }
10756
10757   return Result;
10758 }
10759
10760 SDValue
10761 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10762                                       int64_t Offset, SelectionDAG &DAG) const {
10763   // Create the TargetGlobalAddress node, folding in the constant
10764   // offset if it is legal.
10765   unsigned char OpFlags =
10766       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10767   CodeModel::Model M = DAG.getTarget().getCodeModel();
10768   SDValue Result;
10769   if (OpFlags == X86II::MO_NO_FLAG &&
10770       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10771     // A direct static reference to a global.
10772     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10773     Offset = 0;
10774   } else {
10775     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10776   }
10777
10778   if (Subtarget->isPICStyleRIPRel() &&
10779       (M == CodeModel::Small || M == CodeModel::Kernel))
10780     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10781   else
10782     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10783
10784   // With PIC, the address is actually $g + Offset.
10785   if (isGlobalRelativeToPICBase(OpFlags)) {
10786     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10787                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10788                          Result);
10789   }
10790
10791   // For globals that require a load from a stub to get the address, emit the
10792   // load.
10793   if (isGlobalStubReference(OpFlags))
10794     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10795                          MachinePointerInfo::getGOT(), false, false, false, 0);
10796
10797   // If there was a non-zero offset that we didn't fold, create an explicit
10798   // addition for it.
10799   if (Offset != 0)
10800     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10801                          DAG.getConstant(Offset, getPointerTy()));
10802
10803   return Result;
10804 }
10805
10806 SDValue
10807 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10808   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10809   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10810   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10811 }
10812
10813 static SDValue
10814 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10815            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10816            unsigned char OperandFlags, bool LocalDynamic = false) {
10817   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10818   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10819   SDLoc dl(GA);
10820   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10821                                            GA->getValueType(0),
10822                                            GA->getOffset(),
10823                                            OperandFlags);
10824
10825   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10826                                            : X86ISD::TLSADDR;
10827
10828   if (InFlag) {
10829     SDValue Ops[] = { Chain,  TGA, *InFlag };
10830     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10831   } else {
10832     SDValue Ops[]  = { Chain, TGA };
10833     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10834   }
10835
10836   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10837   MFI->setAdjustsStack(true);
10838   MFI->setHasCalls(true);
10839
10840   SDValue Flag = Chain.getValue(1);
10841   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10842 }
10843
10844 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10845 static SDValue
10846 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10847                                 const EVT PtrVT) {
10848   SDValue InFlag;
10849   SDLoc dl(GA);  // ? function entry point might be better
10850   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10851                                    DAG.getNode(X86ISD::GlobalBaseReg,
10852                                                SDLoc(), PtrVT), InFlag);
10853   InFlag = Chain.getValue(1);
10854
10855   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10856 }
10857
10858 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10859 static SDValue
10860 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10861                                 const EVT PtrVT) {
10862   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10863                     X86::RAX, X86II::MO_TLSGD);
10864 }
10865
10866 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10867                                            SelectionDAG &DAG,
10868                                            const EVT PtrVT,
10869                                            bool is64Bit) {
10870   SDLoc dl(GA);
10871
10872   // Get the start address of the TLS block for this module.
10873   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10874       .getInfo<X86MachineFunctionInfo>();
10875   MFI->incNumLocalDynamicTLSAccesses();
10876
10877   SDValue Base;
10878   if (is64Bit) {
10879     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10880                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10881   } else {
10882     SDValue InFlag;
10883     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10884         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10885     InFlag = Chain.getValue(1);
10886     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10887                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10888   }
10889
10890   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10891   // of Base.
10892
10893   // Build x@dtpoff.
10894   unsigned char OperandFlags = X86II::MO_DTPOFF;
10895   unsigned WrapperKind = X86ISD::Wrapper;
10896   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10897                                            GA->getValueType(0),
10898                                            GA->getOffset(), OperandFlags);
10899   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10900
10901   // Add x@dtpoff with the base.
10902   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10903 }
10904
10905 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10906 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10907                                    const EVT PtrVT, TLSModel::Model model,
10908                                    bool is64Bit, bool isPIC) {
10909   SDLoc dl(GA);
10910
10911   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10912   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10913                                                          is64Bit ? 257 : 256));
10914
10915   SDValue ThreadPointer =
10916       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10917                   MachinePointerInfo(Ptr), false, false, false, 0);
10918
10919   unsigned char OperandFlags = 0;
10920   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10921   // initialexec.
10922   unsigned WrapperKind = X86ISD::Wrapper;
10923   if (model == TLSModel::LocalExec) {
10924     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10925   } else if (model == TLSModel::InitialExec) {
10926     if (is64Bit) {
10927       OperandFlags = X86II::MO_GOTTPOFF;
10928       WrapperKind = X86ISD::WrapperRIP;
10929     } else {
10930       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10931     }
10932   } else {
10933     llvm_unreachable("Unexpected model");
10934   }
10935
10936   // emit "addl x@ntpoff,%eax" (local exec)
10937   // or "addl x@indntpoff,%eax" (initial exec)
10938   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10939   SDValue TGA =
10940       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10941                                  GA->getOffset(), OperandFlags);
10942   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10943
10944   if (model == TLSModel::InitialExec) {
10945     if (isPIC && !is64Bit) {
10946       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10947                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10948                            Offset);
10949     }
10950
10951     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10952                          MachinePointerInfo::getGOT(), false, false, false, 0);
10953   }
10954
10955   // The address of the thread local variable is the add of the thread
10956   // pointer with the offset of the variable.
10957   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10958 }
10959
10960 SDValue
10961 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10962
10963   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10964   const GlobalValue *GV = GA->getGlobal();
10965
10966   if (Subtarget->isTargetELF()) {
10967     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10968
10969     switch (model) {
10970       case TLSModel::GeneralDynamic:
10971         if (Subtarget->is64Bit())
10972           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10973         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10974       case TLSModel::LocalDynamic:
10975         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10976                                            Subtarget->is64Bit());
10977       case TLSModel::InitialExec:
10978       case TLSModel::LocalExec:
10979         return LowerToTLSExecModel(
10980             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10981             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10982     }
10983     llvm_unreachable("Unknown TLS model.");
10984   }
10985
10986   if (Subtarget->isTargetDarwin()) {
10987     // Darwin only has one model of TLS.  Lower to that.
10988     unsigned char OpFlag = 0;
10989     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10990                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10991
10992     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10993     // global base reg.
10994     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10995                  !Subtarget->is64Bit();
10996     if (PIC32)
10997       OpFlag = X86II::MO_TLVP_PIC_BASE;
10998     else
10999       OpFlag = X86II::MO_TLVP;
11000     SDLoc DL(Op);
11001     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11002                                                 GA->getValueType(0),
11003                                                 GA->getOffset(), OpFlag);
11004     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11005
11006     // With PIC32, the address is actually $g + Offset.
11007     if (PIC32)
11008       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11009                            DAG.getNode(X86ISD::GlobalBaseReg,
11010                                        SDLoc(), getPointerTy()),
11011                            Offset);
11012
11013     // Lowering the machine isd will make sure everything is in the right
11014     // location.
11015     SDValue Chain = DAG.getEntryNode();
11016     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11017     SDValue Args[] = { Chain, Offset };
11018     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11019
11020     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11021     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11022     MFI->setAdjustsStack(true);
11023
11024     // And our return value (tls address) is in the standard call return value
11025     // location.
11026     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11027     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11028                               Chain.getValue(1));
11029   }
11030
11031   if (Subtarget->isTargetKnownWindowsMSVC() ||
11032       Subtarget->isTargetWindowsGNU()) {
11033     // Just use the implicit TLS architecture
11034     // Need to generate someting similar to:
11035     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11036     //                                  ; from TEB
11037     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11038     //   mov     rcx, qword [rdx+rcx*8]
11039     //   mov     eax, .tls$:tlsvar
11040     //   [rax+rcx] contains the address
11041     // Windows 64bit: gs:0x58
11042     // Windows 32bit: fs:__tls_array
11043
11044     SDLoc dl(GA);
11045     SDValue Chain = DAG.getEntryNode();
11046
11047     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11048     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11049     // use its literal value of 0x2C.
11050     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11051                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11052                                                              256)
11053                                         : Type::getInt32PtrTy(*DAG.getContext(),
11054                                                               257));
11055
11056     SDValue TlsArray =
11057         Subtarget->is64Bit()
11058             ? DAG.getIntPtrConstant(0x58)
11059             : (Subtarget->isTargetWindowsGNU()
11060                    ? DAG.getIntPtrConstant(0x2C)
11061                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11062
11063     SDValue ThreadPointer =
11064         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11065                     MachinePointerInfo(Ptr), false, false, false, 0);
11066
11067     // Load the _tls_index variable
11068     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11069     if (Subtarget->is64Bit())
11070       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11071                            IDX, MachinePointerInfo(), MVT::i32,
11072                            false, false, false, 0);
11073     else
11074       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11075                         false, false, false, 0);
11076
11077     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11078                                     getPointerTy());
11079     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11080
11081     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11082     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11083                       false, false, false, 0);
11084
11085     // Get the offset of start of .tls section
11086     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11087                                              GA->getValueType(0),
11088                                              GA->getOffset(), X86II::MO_SECREL);
11089     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11090
11091     // The address of the thread local variable is the add of the thread
11092     // pointer with the offset of the variable.
11093     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11094   }
11095
11096   llvm_unreachable("TLS not implemented for this target.");
11097 }
11098
11099 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11100 /// and take a 2 x i32 value to shift plus a shift amount.
11101 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11102   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11103   MVT VT = Op.getSimpleValueType();
11104   unsigned VTBits = VT.getSizeInBits();
11105   SDLoc dl(Op);
11106   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11107   SDValue ShOpLo = Op.getOperand(0);
11108   SDValue ShOpHi = Op.getOperand(1);
11109   SDValue ShAmt  = Op.getOperand(2);
11110   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11111   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11112   // during isel.
11113   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11114                                   DAG.getConstant(VTBits - 1, MVT::i8));
11115   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11116                                      DAG.getConstant(VTBits - 1, MVT::i8))
11117                        : DAG.getConstant(0, VT);
11118
11119   SDValue Tmp2, Tmp3;
11120   if (Op.getOpcode() == ISD::SHL_PARTS) {
11121     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11122     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11123   } else {
11124     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11125     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11126   }
11127
11128   // If the shift amount is larger or equal than the width of a part we can't
11129   // rely on the results of shld/shrd. Insert a test and select the appropriate
11130   // values for large shift amounts.
11131   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11132                                 DAG.getConstant(VTBits, MVT::i8));
11133   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11134                              AndNode, DAG.getConstant(0, MVT::i8));
11135
11136   SDValue Hi, Lo;
11137   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11138   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11139   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11140
11141   if (Op.getOpcode() == ISD::SHL_PARTS) {
11142     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11143     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11144   } else {
11145     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11146     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11147   }
11148
11149   SDValue Ops[2] = { Lo, Hi };
11150   return DAG.getMergeValues(Ops, dl);
11151 }
11152
11153 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11154                                            SelectionDAG &DAG) const {
11155   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11156   SDLoc dl(Op);
11157
11158   if (SrcVT.isVector()) {
11159     if (SrcVT.getVectorElementType() == MVT::i1) {
11160       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11161       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11162                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11163                                      Op.getOperand(0)));
11164     }
11165     return SDValue();
11166   }
11167
11168   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11169          "Unknown SINT_TO_FP to lower!");
11170
11171   // These are really Legal; return the operand so the caller accepts it as
11172   // Legal.
11173   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11174     return Op;
11175   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11176       Subtarget->is64Bit()) {
11177     return Op;
11178   }
11179
11180   unsigned Size = SrcVT.getSizeInBits()/8;
11181   MachineFunction &MF = DAG.getMachineFunction();
11182   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11183   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11184   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11185                                StackSlot,
11186                                MachinePointerInfo::getFixedStack(SSFI),
11187                                false, false, 0);
11188   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11189 }
11190
11191 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11192                                      SDValue StackSlot,
11193                                      SelectionDAG &DAG) const {
11194   // Build the FILD
11195   SDLoc DL(Op);
11196   SDVTList Tys;
11197   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11198   if (useSSE)
11199     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11200   else
11201     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11202
11203   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11204
11205   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11206   MachineMemOperand *MMO;
11207   if (FI) {
11208     int SSFI = FI->getIndex();
11209     MMO =
11210       DAG.getMachineFunction()
11211       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11212                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11213   } else {
11214     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11215     StackSlot = StackSlot.getOperand(1);
11216   }
11217   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11218   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11219                                            X86ISD::FILD, DL,
11220                                            Tys, Ops, SrcVT, MMO);
11221
11222   if (useSSE) {
11223     Chain = Result.getValue(1);
11224     SDValue InFlag = Result.getValue(2);
11225
11226     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11227     // shouldn't be necessary except that RFP cannot be live across
11228     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11229     MachineFunction &MF = DAG.getMachineFunction();
11230     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11231     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11232     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11233     Tys = DAG.getVTList(MVT::Other);
11234     SDValue Ops[] = {
11235       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11236     };
11237     MachineMemOperand *MMO =
11238       DAG.getMachineFunction()
11239       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11240                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11241
11242     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11243                                     Ops, Op.getValueType(), MMO);
11244     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11245                          MachinePointerInfo::getFixedStack(SSFI),
11246                          false, false, false, 0);
11247   }
11248
11249   return Result;
11250 }
11251
11252 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11253 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11254                                                SelectionDAG &DAG) const {
11255   // This algorithm is not obvious. Here it is what we're trying to output:
11256   /*
11257      movq       %rax,  %xmm0
11258      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11259      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11260      #ifdef __SSE3__
11261        haddpd   %xmm0, %xmm0
11262      #else
11263        pshufd   $0x4e, %xmm0, %xmm1
11264        addpd    %xmm1, %xmm0
11265      #endif
11266   */
11267
11268   SDLoc dl(Op);
11269   LLVMContext *Context = DAG.getContext();
11270
11271   // Build some magic constants.
11272   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11273   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11274   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11275
11276   SmallVector<Constant*,2> CV1;
11277   CV1.push_back(
11278     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11279                                       APInt(64, 0x4330000000000000ULL))));
11280   CV1.push_back(
11281     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11282                                       APInt(64, 0x4530000000000000ULL))));
11283   Constant *C1 = ConstantVector::get(CV1);
11284   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11285
11286   // Load the 64-bit value into an XMM register.
11287   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11288                             Op.getOperand(0));
11289   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11290                               MachinePointerInfo::getConstantPool(),
11291                               false, false, false, 16);
11292   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11293                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11294                               CLod0);
11295
11296   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11297                               MachinePointerInfo::getConstantPool(),
11298                               false, false, false, 16);
11299   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11300   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11301   SDValue Result;
11302
11303   if (Subtarget->hasSSE3()) {
11304     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11305     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11306   } else {
11307     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11308     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11309                                            S2F, 0x4E, DAG);
11310     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11311                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11312                          Sub);
11313   }
11314
11315   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11316                      DAG.getIntPtrConstant(0));
11317 }
11318
11319 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11320 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11321                                                SelectionDAG &DAG) const {
11322   SDLoc dl(Op);
11323   // FP constant to bias correct the final result.
11324   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11325                                    MVT::f64);
11326
11327   // Load the 32-bit value into an XMM register.
11328   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11329                              Op.getOperand(0));
11330
11331   // Zero out the upper parts of the register.
11332   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11333
11334   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11335                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11336                      DAG.getIntPtrConstant(0));
11337
11338   // Or the load with the bias.
11339   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11340                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11341                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11342                                                    MVT::v2f64, Load)),
11343                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11344                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11345                                                    MVT::v2f64, Bias)));
11346   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11347                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11348                    DAG.getIntPtrConstant(0));
11349
11350   // Subtract the bias.
11351   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11352
11353   // Handle final rounding.
11354   EVT DestVT = Op.getValueType();
11355
11356   if (DestVT.bitsLT(MVT::f64))
11357     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11358                        DAG.getIntPtrConstant(0));
11359   if (DestVT.bitsGT(MVT::f64))
11360     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11361
11362   // Handle final rounding.
11363   return Sub;
11364 }
11365
11366 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11367                                      const X86Subtarget &Subtarget) {
11368   // The algorithm is the following:
11369   // #ifdef __SSE4_1__
11370   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11371   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11372   //                                 (uint4) 0x53000000, 0xaa);
11373   // #else
11374   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11375   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11376   // #endif
11377   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11378   //     return (float4) lo + fhi;
11379
11380   SDLoc DL(Op);
11381   SDValue V = Op->getOperand(0);
11382   EVT VecIntVT = V.getValueType();
11383   bool Is128 = VecIntVT == MVT::v4i32;
11384   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11385   // If we convert to something else than the supported type, e.g., to v4f64,
11386   // abort early.
11387   if (VecFloatVT != Op->getValueType(0))
11388     return SDValue();
11389
11390   unsigned NumElts = VecIntVT.getVectorNumElements();
11391   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11392          "Unsupported custom type");
11393   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11394
11395   // In the #idef/#else code, we have in common:
11396   // - The vector of constants:
11397   // -- 0x4b000000
11398   // -- 0x53000000
11399   // - A shift:
11400   // -- v >> 16
11401
11402   // Create the splat vector for 0x4b000000.
11403   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11404   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11405                            CstLow, CstLow, CstLow, CstLow};
11406   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11407                                   makeArrayRef(&CstLowArray[0], NumElts));
11408   // Create the splat vector for 0x53000000.
11409   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11410   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11411                             CstHigh, CstHigh, CstHigh, CstHigh};
11412   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11413                                    makeArrayRef(&CstHighArray[0], NumElts));
11414
11415   // Create the right shift.
11416   SDValue CstShift = DAG.getConstant(16, MVT::i32);
11417   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11418                              CstShift, CstShift, CstShift, CstShift};
11419   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11420                                     makeArrayRef(&CstShiftArray[0], NumElts));
11421   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11422
11423   SDValue Low, High;
11424   if (Subtarget.hasSSE41()) {
11425     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11426     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11427     SDValue VecCstLowBitcast =
11428         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11429     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11430     // Low will be bitcasted right away, so do not bother bitcasting back to its
11431     // original type.
11432     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11433                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11434     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11435     //                                 (uint4) 0x53000000, 0xaa);
11436     SDValue VecCstHighBitcast =
11437         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11438     SDValue VecShiftBitcast =
11439         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11440     // High will be bitcasted right away, so do not bother bitcasting back to
11441     // its original type.
11442     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11443                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11444   } else {
11445     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11446     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11447                                      CstMask, CstMask, CstMask);
11448     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11449     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11450     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11451
11452     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11453     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11454   }
11455
11456   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11457   SDValue CstFAdd = DAG.getConstantFP(
11458       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11459   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11460                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11461   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11462                                    makeArrayRef(&CstFAddArray[0], NumElts));
11463
11464   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11465   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11466   SDValue FHigh =
11467       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11468   //     return (float4) lo + fhi;
11469   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11470   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11471 }
11472
11473 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11474                                                SelectionDAG &DAG) const {
11475   SDValue N0 = Op.getOperand(0);
11476   MVT SVT = N0.getSimpleValueType();
11477   SDLoc dl(Op);
11478
11479   switch (SVT.SimpleTy) {
11480   default:
11481     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11482   case MVT::v4i8:
11483   case MVT::v4i16:
11484   case MVT::v8i8:
11485   case MVT::v8i16: {
11486     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11487     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11488                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11489   }
11490   case MVT::v4i32:
11491   case MVT::v8i32:
11492     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11493   }
11494   llvm_unreachable(nullptr);
11495 }
11496
11497 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11498                                            SelectionDAG &DAG) const {
11499   SDValue N0 = Op.getOperand(0);
11500   SDLoc dl(Op);
11501
11502   if (Op.getValueType().isVector())
11503     return lowerUINT_TO_FP_vec(Op, DAG);
11504
11505   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11506   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11507   // the optimization here.
11508   if (DAG.SignBitIsZero(N0))
11509     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11510
11511   MVT SrcVT = N0.getSimpleValueType();
11512   MVT DstVT = Op.getSimpleValueType();
11513   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11514     return LowerUINT_TO_FP_i64(Op, DAG);
11515   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11516     return LowerUINT_TO_FP_i32(Op, DAG);
11517   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11518     return SDValue();
11519
11520   // Make a 64-bit buffer, and use it to build an FILD.
11521   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11522   if (SrcVT == MVT::i32) {
11523     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11524     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11525                                      getPointerTy(), StackSlot, WordOff);
11526     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11527                                   StackSlot, MachinePointerInfo(),
11528                                   false, false, 0);
11529     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11530                                   OffsetSlot, MachinePointerInfo(),
11531                                   false, false, 0);
11532     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11533     return Fild;
11534   }
11535
11536   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11537   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11538                                StackSlot, MachinePointerInfo(),
11539                                false, false, 0);
11540   // For i64 source, we need to add the appropriate power of 2 if the input
11541   // was negative.  This is the same as the optimization in
11542   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11543   // we must be careful to do the computation in x87 extended precision, not
11544   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11545   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11546   MachineMemOperand *MMO =
11547     DAG.getMachineFunction()
11548     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11549                           MachineMemOperand::MOLoad, 8, 8);
11550
11551   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11552   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11553   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11554                                          MVT::i64, MMO);
11555
11556   APInt FF(32, 0x5F800000ULL);
11557
11558   // Check whether the sign bit is set.
11559   SDValue SignSet = DAG.getSetCC(dl,
11560                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11561                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11562                                  ISD::SETLT);
11563
11564   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11565   SDValue FudgePtr = DAG.getConstantPool(
11566                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11567                                          getPointerTy());
11568
11569   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11570   SDValue Zero = DAG.getIntPtrConstant(0);
11571   SDValue Four = DAG.getIntPtrConstant(4);
11572   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11573                                Zero, Four);
11574   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11575
11576   // Load the value out, extending it from f32 to f80.
11577   // FIXME: Avoid the extend by constructing the right constant pool?
11578   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11579                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11580                                  MVT::f32, false, false, false, 4);
11581   // Extend everything to 80 bits to force it to be done on x87.
11582   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11583   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11584 }
11585
11586 std::pair<SDValue,SDValue>
11587 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11588                                     bool IsSigned, bool IsReplace) const {
11589   SDLoc DL(Op);
11590
11591   EVT DstTy = Op.getValueType();
11592
11593   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11594     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11595     DstTy = MVT::i64;
11596   }
11597
11598   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11599          DstTy.getSimpleVT() >= MVT::i16 &&
11600          "Unknown FP_TO_INT to lower!");
11601
11602   // These are really Legal.
11603   if (DstTy == MVT::i32 &&
11604       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11605     return std::make_pair(SDValue(), SDValue());
11606   if (Subtarget->is64Bit() &&
11607       DstTy == MVT::i64 &&
11608       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11609     return std::make_pair(SDValue(), SDValue());
11610
11611   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11612   // stack slot, or into the FTOL runtime function.
11613   MachineFunction &MF = DAG.getMachineFunction();
11614   unsigned MemSize = DstTy.getSizeInBits()/8;
11615   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11616   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11617
11618   unsigned Opc;
11619   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11620     Opc = X86ISD::WIN_FTOL;
11621   else
11622     switch (DstTy.getSimpleVT().SimpleTy) {
11623     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11624     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11625     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11626     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11627     }
11628
11629   SDValue Chain = DAG.getEntryNode();
11630   SDValue Value = Op.getOperand(0);
11631   EVT TheVT = Op.getOperand(0).getValueType();
11632   // FIXME This causes a redundant load/store if the SSE-class value is already
11633   // in memory, such as if it is on the callstack.
11634   if (isScalarFPTypeInSSEReg(TheVT)) {
11635     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11636     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11637                          MachinePointerInfo::getFixedStack(SSFI),
11638                          false, false, 0);
11639     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11640     SDValue Ops[] = {
11641       Chain, StackSlot, DAG.getValueType(TheVT)
11642     };
11643
11644     MachineMemOperand *MMO =
11645       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11646                               MachineMemOperand::MOLoad, MemSize, MemSize);
11647     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11648     Chain = Value.getValue(1);
11649     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11650     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11651   }
11652
11653   MachineMemOperand *MMO =
11654     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11655                             MachineMemOperand::MOStore, MemSize, MemSize);
11656
11657   if (Opc != X86ISD::WIN_FTOL) {
11658     // Build the FP_TO_INT*_IN_MEM
11659     SDValue Ops[] = { Chain, Value, StackSlot };
11660     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11661                                            Ops, DstTy, MMO);
11662     return std::make_pair(FIST, StackSlot);
11663   } else {
11664     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11665       DAG.getVTList(MVT::Other, MVT::Glue),
11666       Chain, Value);
11667     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11668       MVT::i32, ftol.getValue(1));
11669     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11670       MVT::i32, eax.getValue(2));
11671     SDValue Ops[] = { eax, edx };
11672     SDValue pair = IsReplace
11673       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11674       : DAG.getMergeValues(Ops, DL);
11675     return std::make_pair(pair, SDValue());
11676   }
11677 }
11678
11679 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11680                               const X86Subtarget *Subtarget) {
11681   MVT VT = Op->getSimpleValueType(0);
11682   SDValue In = Op->getOperand(0);
11683   MVT InVT = In.getSimpleValueType();
11684   SDLoc dl(Op);
11685
11686   // Optimize vectors in AVX mode:
11687   //
11688   //   v8i16 -> v8i32
11689   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11690   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11691   //   Concat upper and lower parts.
11692   //
11693   //   v4i32 -> v4i64
11694   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11695   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11696   //   Concat upper and lower parts.
11697   //
11698
11699   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11700       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11701       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11702     return SDValue();
11703
11704   if (Subtarget->hasInt256())
11705     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11706
11707   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11708   SDValue Undef = DAG.getUNDEF(InVT);
11709   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11710   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11711   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11712
11713   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11714                              VT.getVectorNumElements()/2);
11715
11716   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11717   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11718
11719   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11720 }
11721
11722 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11723                                         SelectionDAG &DAG) {
11724   MVT VT = Op->getSimpleValueType(0);
11725   SDValue In = Op->getOperand(0);
11726   MVT InVT = In.getSimpleValueType();
11727   SDLoc DL(Op);
11728   unsigned int NumElts = VT.getVectorNumElements();
11729   if (NumElts != 8 && NumElts != 16)
11730     return SDValue();
11731
11732   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11733     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11734
11735   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11737   // Now we have only mask extension
11738   assert(InVT.getVectorElementType() == MVT::i1);
11739   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11740   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11741   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11742   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11743   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11744                            MachinePointerInfo::getConstantPool(),
11745                            false, false, false, Alignment);
11746
11747   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11748   if (VT.is512BitVector())
11749     return Brcst;
11750   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11751 }
11752
11753 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11754                                SelectionDAG &DAG) {
11755   if (Subtarget->hasFp256()) {
11756     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11757     if (Res.getNode())
11758       return Res;
11759   }
11760
11761   return SDValue();
11762 }
11763
11764 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11765                                 SelectionDAG &DAG) {
11766   SDLoc DL(Op);
11767   MVT VT = Op.getSimpleValueType();
11768   SDValue In = Op.getOperand(0);
11769   MVT SVT = In.getSimpleValueType();
11770
11771   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11772     return LowerZERO_EXTEND_AVX512(Op, DAG);
11773
11774   if (Subtarget->hasFp256()) {
11775     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11776     if (Res.getNode())
11777       return Res;
11778   }
11779
11780   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11781          VT.getVectorNumElements() != SVT.getVectorNumElements());
11782   return SDValue();
11783 }
11784
11785 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11786   SDLoc DL(Op);
11787   MVT VT = Op.getSimpleValueType();
11788   SDValue In = Op.getOperand(0);
11789   MVT InVT = In.getSimpleValueType();
11790
11791   if (VT == MVT::i1) {
11792     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11793            "Invalid scalar TRUNCATE operation");
11794     if (InVT.getSizeInBits() >= 32)
11795       return SDValue();
11796     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11797     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11798   }
11799   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11800          "Invalid TRUNCATE operation");
11801
11802   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11803     if (VT.getVectorElementType().getSizeInBits() >=8)
11804       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11805
11806     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11807     unsigned NumElts = InVT.getVectorNumElements();
11808     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11809     if (InVT.getSizeInBits() < 512) {
11810       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11811       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11812       InVT = ExtVT;
11813     }
11814
11815     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11816     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11817     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11818     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11819     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11820                            MachinePointerInfo::getConstantPool(),
11821                            false, false, false, Alignment);
11822     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11823     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11824     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11825   }
11826
11827   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11828     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11829     if (Subtarget->hasInt256()) {
11830       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11831       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11832       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11833                                 ShufMask);
11834       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11835                          DAG.getIntPtrConstant(0));
11836     }
11837
11838     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11839                                DAG.getIntPtrConstant(0));
11840     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11841                                DAG.getIntPtrConstant(2));
11842     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11843     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11844     static const int ShufMask[] = {0, 2, 4, 6};
11845     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11846   }
11847
11848   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11849     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11850     if (Subtarget->hasInt256()) {
11851       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11852
11853       SmallVector<SDValue,32> pshufbMask;
11854       for (unsigned i = 0; i < 2; ++i) {
11855         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11856         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11857         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11858         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11859         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11860         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11861         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11862         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11863         for (unsigned j = 0; j < 8; ++j)
11864           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11865       }
11866       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11867       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11868       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11869
11870       static const int ShufMask[] = {0,  2,  -1,  -1};
11871       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11872                                 &ShufMask[0]);
11873       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11874                        DAG.getIntPtrConstant(0));
11875       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11876     }
11877
11878     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11879                                DAG.getIntPtrConstant(0));
11880
11881     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11882                                DAG.getIntPtrConstant(4));
11883
11884     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11885     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11886
11887     // The PSHUFB mask:
11888     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11889                                    -1, -1, -1, -1, -1, -1, -1, -1};
11890
11891     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11892     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11893     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11894
11895     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11896     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11897
11898     // The MOVLHPS Mask:
11899     static const int ShufMask2[] = {0, 1, 4, 5};
11900     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11901     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11902   }
11903
11904   // Handle truncation of V256 to V128 using shuffles.
11905   if (!VT.is128BitVector() || !InVT.is256BitVector())
11906     return SDValue();
11907
11908   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11909
11910   unsigned NumElems = VT.getVectorNumElements();
11911   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11912
11913   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11914   // Prepare truncation shuffle mask
11915   for (unsigned i = 0; i != NumElems; ++i)
11916     MaskVec[i] = i * 2;
11917   SDValue V = DAG.getVectorShuffle(NVT, DL,
11918                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11919                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11920   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11921                      DAG.getIntPtrConstant(0));
11922 }
11923
11924 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11925                                            SelectionDAG &DAG) const {
11926   assert(!Op.getSimpleValueType().isVector());
11927
11928   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11929     /*IsSigned=*/ true, /*IsReplace=*/ false);
11930   SDValue FIST = Vals.first, StackSlot = Vals.second;
11931   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11932   if (!FIST.getNode()) return Op;
11933
11934   if (StackSlot.getNode())
11935     // Load the result.
11936     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11937                        FIST, StackSlot, MachinePointerInfo(),
11938                        false, false, false, 0);
11939
11940   // The node is the result.
11941   return FIST;
11942 }
11943
11944 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11945                                            SelectionDAG &DAG) const {
11946   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11947     /*IsSigned=*/ false, /*IsReplace=*/ false);
11948   SDValue FIST = Vals.first, StackSlot = Vals.second;
11949   assert(FIST.getNode() && "Unexpected failure");
11950
11951   if (StackSlot.getNode())
11952     // Load the result.
11953     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11954                        FIST, StackSlot, MachinePointerInfo(),
11955                        false, false, false, 0);
11956
11957   // The node is the result.
11958   return FIST;
11959 }
11960
11961 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11962   SDLoc DL(Op);
11963   MVT VT = Op.getSimpleValueType();
11964   SDValue In = Op.getOperand(0);
11965   MVT SVT = In.getSimpleValueType();
11966
11967   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11968
11969   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11970                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11971                                  In, DAG.getUNDEF(SVT)));
11972 }
11973
11974 /// The only differences between FABS and FNEG are the mask and the logic op.
11975 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
11976 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
11977   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
11978          "Wrong opcode for lowering FABS or FNEG.");
11979
11980   bool IsFABS = (Op.getOpcode() == ISD::FABS);
11981
11982   // If this is a FABS and it has an FNEG user, bail out to fold the combination
11983   // into an FNABS. We'll lower the FABS after that if it is still in use.
11984   if (IsFABS)
11985     for (SDNode *User : Op->uses())
11986       if (User->getOpcode() == ISD::FNEG)
11987         return Op;
11988
11989   SDValue Op0 = Op.getOperand(0);
11990   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
11991
11992   SDLoc dl(Op);
11993   MVT VT = Op.getSimpleValueType();
11994   // Assume scalar op for initialization; update for vector if needed.
11995   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
11996   // generate a 16-byte vector constant and logic op even for the scalar case.
11997   // Using a 16-byte mask allows folding the load of the mask with
11998   // the logic op, so it can save (~4 bytes) on code size.
11999   MVT EltVT = VT;
12000   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12001   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12002   // decide if we should generate a 16-byte constant mask when we only need 4 or
12003   // 8 bytes for the scalar case.
12004   if (VT.isVector()) {
12005     EltVT = VT.getVectorElementType();
12006     NumElts = VT.getVectorNumElements();
12007   }
12008
12009   unsigned EltBits = EltVT.getSizeInBits();
12010   LLVMContext *Context = DAG.getContext();
12011   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12012   APInt MaskElt =
12013     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12014   Constant *C = ConstantInt::get(*Context, MaskElt);
12015   C = ConstantVector::getSplat(NumElts, C);
12016   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12017   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12018   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12019   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12020                              MachinePointerInfo::getConstantPool(),
12021                              false, false, false, Alignment);
12022
12023   if (VT.isVector()) {
12024     // For a vector, cast operands to a vector type, perform the logic op,
12025     // and cast the result back to the original value type.
12026     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12027     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12028     SDValue Operand = IsFNABS ?
12029       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12030       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12031     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12032     return DAG.getNode(ISD::BITCAST, dl, VT,
12033                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12034   }
12035
12036   // If not vector, then scalar.
12037   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12038   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12039   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12040 }
12041
12042 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12043   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12044   LLVMContext *Context = DAG.getContext();
12045   SDValue Op0 = Op.getOperand(0);
12046   SDValue Op1 = Op.getOperand(1);
12047   SDLoc dl(Op);
12048   MVT VT = Op.getSimpleValueType();
12049   MVT SrcVT = Op1.getSimpleValueType();
12050
12051   // If second operand is smaller, extend it first.
12052   if (SrcVT.bitsLT(VT)) {
12053     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12054     SrcVT = VT;
12055   }
12056   // And if it is bigger, shrink it first.
12057   if (SrcVT.bitsGT(VT)) {
12058     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12059     SrcVT = VT;
12060   }
12061
12062   // At this point the operands and the result should have the same
12063   // type, and that won't be f80 since that is not custom lowered.
12064
12065   const fltSemantics &Sem =
12066       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12067   const unsigned SizeInBits = VT.getSizeInBits();
12068
12069   SmallVector<Constant *, 4> CV(
12070       VT == MVT::f64 ? 2 : 4,
12071       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12072
12073   // First, clear all bits but the sign bit from the second operand (sign).
12074   CV[0] = ConstantFP::get(*Context,
12075                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12076   Constant *C = ConstantVector::get(CV);
12077   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12078   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12079                               MachinePointerInfo::getConstantPool(),
12080                               false, false, false, 16);
12081   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12082
12083   // Next, clear the sign bit from the first operand (magnitude).
12084   // If it's a constant, we can clear it here.
12085   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12086     APFloat APF = Op0CN->getValueAPF();
12087     // If the magnitude is a positive zero, the sign bit alone is enough.
12088     if (APF.isPosZero())
12089       return SignBit;
12090     APF.clearSign();
12091     CV[0] = ConstantFP::get(*Context, APF);
12092   } else {
12093     CV[0] = ConstantFP::get(
12094         *Context,
12095         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12096   }
12097   C = ConstantVector::get(CV);
12098   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12099   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12100                             MachinePointerInfo::getConstantPool(),
12101                             false, false, false, 16);
12102   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12103   if (!isa<ConstantFPSDNode>(Op0))
12104     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12105
12106   // OR the magnitude value with the sign bit.
12107   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12108 }
12109
12110 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12111   SDValue N0 = Op.getOperand(0);
12112   SDLoc dl(Op);
12113   MVT VT = Op.getSimpleValueType();
12114
12115   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12116   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12117                                   DAG.getConstant(1, VT));
12118   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12119 }
12120
12121 // Check whether an OR'd tree is PTEST-able.
12122 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12123                                       SelectionDAG &DAG) {
12124   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12125
12126   if (!Subtarget->hasSSE41())
12127     return SDValue();
12128
12129   if (!Op->hasOneUse())
12130     return SDValue();
12131
12132   SDNode *N = Op.getNode();
12133   SDLoc DL(N);
12134
12135   SmallVector<SDValue, 8> Opnds;
12136   DenseMap<SDValue, unsigned> VecInMap;
12137   SmallVector<SDValue, 8> VecIns;
12138   EVT VT = MVT::Other;
12139
12140   // Recognize a special case where a vector is casted into wide integer to
12141   // test all 0s.
12142   Opnds.push_back(N->getOperand(0));
12143   Opnds.push_back(N->getOperand(1));
12144
12145   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12146     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12147     // BFS traverse all OR'd operands.
12148     if (I->getOpcode() == ISD::OR) {
12149       Opnds.push_back(I->getOperand(0));
12150       Opnds.push_back(I->getOperand(1));
12151       // Re-evaluate the number of nodes to be traversed.
12152       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12153       continue;
12154     }
12155
12156     // Quit if a non-EXTRACT_VECTOR_ELT
12157     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12158       return SDValue();
12159
12160     // Quit if without a constant index.
12161     SDValue Idx = I->getOperand(1);
12162     if (!isa<ConstantSDNode>(Idx))
12163       return SDValue();
12164
12165     SDValue ExtractedFromVec = I->getOperand(0);
12166     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12167     if (M == VecInMap.end()) {
12168       VT = ExtractedFromVec.getValueType();
12169       // Quit if not 128/256-bit vector.
12170       if (!VT.is128BitVector() && !VT.is256BitVector())
12171         return SDValue();
12172       // Quit if not the same type.
12173       if (VecInMap.begin() != VecInMap.end() &&
12174           VT != VecInMap.begin()->first.getValueType())
12175         return SDValue();
12176       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12177       VecIns.push_back(ExtractedFromVec);
12178     }
12179     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12180   }
12181
12182   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12183          "Not extracted from 128-/256-bit vector.");
12184
12185   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12186
12187   for (DenseMap<SDValue, unsigned>::const_iterator
12188         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12189     // Quit if not all elements are used.
12190     if (I->second != FullMask)
12191       return SDValue();
12192   }
12193
12194   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12195
12196   // Cast all vectors into TestVT for PTEST.
12197   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12198     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12199
12200   // If more than one full vectors are evaluated, OR them first before PTEST.
12201   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12202     // Each iteration will OR 2 nodes and append the result until there is only
12203     // 1 node left, i.e. the final OR'd value of all vectors.
12204     SDValue LHS = VecIns[Slot];
12205     SDValue RHS = VecIns[Slot + 1];
12206     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12207   }
12208
12209   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12210                      VecIns.back(), VecIns.back());
12211 }
12212
12213 /// \brief return true if \c Op has a use that doesn't just read flags.
12214 static bool hasNonFlagsUse(SDValue Op) {
12215   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12216        ++UI) {
12217     SDNode *User = *UI;
12218     unsigned UOpNo = UI.getOperandNo();
12219     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12220       // Look pass truncate.
12221       UOpNo = User->use_begin().getOperandNo();
12222       User = *User->use_begin();
12223     }
12224
12225     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12226         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12227       return true;
12228   }
12229   return false;
12230 }
12231
12232 /// Emit nodes that will be selected as "test Op0,Op0", or something
12233 /// equivalent.
12234 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12235                                     SelectionDAG &DAG) const {
12236   if (Op.getValueType() == MVT::i1) {
12237     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12238     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12239                        DAG.getConstant(0, MVT::i8));
12240   }
12241   // CF and OF aren't always set the way we want. Determine which
12242   // of these we need.
12243   bool NeedCF = false;
12244   bool NeedOF = false;
12245   switch (X86CC) {
12246   default: break;
12247   case X86::COND_A: case X86::COND_AE:
12248   case X86::COND_B: case X86::COND_BE:
12249     NeedCF = true;
12250     break;
12251   case X86::COND_G: case X86::COND_GE:
12252   case X86::COND_L: case X86::COND_LE:
12253   case X86::COND_O: case X86::COND_NO: {
12254     // Check if we really need to set the
12255     // Overflow flag. If NoSignedWrap is present
12256     // that is not actually needed.
12257     switch (Op->getOpcode()) {
12258     case ISD::ADD:
12259     case ISD::SUB:
12260     case ISD::MUL:
12261     case ISD::SHL: {
12262       const BinaryWithFlagsSDNode *BinNode =
12263           cast<BinaryWithFlagsSDNode>(Op.getNode());
12264       if (BinNode->hasNoSignedWrap())
12265         break;
12266     }
12267     default:
12268       NeedOF = true;
12269       break;
12270     }
12271     break;
12272   }
12273   }
12274   // See if we can use the EFLAGS value from the operand instead of
12275   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12276   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12277   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12278     // Emit a CMP with 0, which is the TEST pattern.
12279     //if (Op.getValueType() == MVT::i1)
12280     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12281     //                     DAG.getConstant(0, MVT::i1));
12282     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12283                        DAG.getConstant(0, Op.getValueType()));
12284   }
12285   unsigned Opcode = 0;
12286   unsigned NumOperands = 0;
12287
12288   // Truncate operations may prevent the merge of the SETCC instruction
12289   // and the arithmetic instruction before it. Attempt to truncate the operands
12290   // of the arithmetic instruction and use a reduced bit-width instruction.
12291   bool NeedTruncation = false;
12292   SDValue ArithOp = Op;
12293   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12294     SDValue Arith = Op->getOperand(0);
12295     // Both the trunc and the arithmetic op need to have one user each.
12296     if (Arith->hasOneUse())
12297       switch (Arith.getOpcode()) {
12298         default: break;
12299         case ISD::ADD:
12300         case ISD::SUB:
12301         case ISD::AND:
12302         case ISD::OR:
12303         case ISD::XOR: {
12304           NeedTruncation = true;
12305           ArithOp = Arith;
12306         }
12307       }
12308   }
12309
12310   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12311   // which may be the result of a CAST.  We use the variable 'Op', which is the
12312   // non-casted variable when we check for possible users.
12313   switch (ArithOp.getOpcode()) {
12314   case ISD::ADD:
12315     // Due to an isel shortcoming, be conservative if this add is likely to be
12316     // selected as part of a load-modify-store instruction. When the root node
12317     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12318     // uses of other nodes in the match, such as the ADD in this case. This
12319     // leads to the ADD being left around and reselected, with the result being
12320     // two adds in the output.  Alas, even if none our users are stores, that
12321     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12322     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12323     // climbing the DAG back to the root, and it doesn't seem to be worth the
12324     // effort.
12325     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12326          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12327       if (UI->getOpcode() != ISD::CopyToReg &&
12328           UI->getOpcode() != ISD::SETCC &&
12329           UI->getOpcode() != ISD::STORE)
12330         goto default_case;
12331
12332     if (ConstantSDNode *C =
12333         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12334       // An add of one will be selected as an INC.
12335       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12336         Opcode = X86ISD::INC;
12337         NumOperands = 1;
12338         break;
12339       }
12340
12341       // An add of negative one (subtract of one) will be selected as a DEC.
12342       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12343         Opcode = X86ISD::DEC;
12344         NumOperands = 1;
12345         break;
12346       }
12347     }
12348
12349     // Otherwise use a regular EFLAGS-setting add.
12350     Opcode = X86ISD::ADD;
12351     NumOperands = 2;
12352     break;
12353   case ISD::SHL:
12354   case ISD::SRL:
12355     // If we have a constant logical shift that's only used in a comparison
12356     // against zero turn it into an equivalent AND. This allows turning it into
12357     // a TEST instruction later.
12358     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12359         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12360       EVT VT = Op.getValueType();
12361       unsigned BitWidth = VT.getSizeInBits();
12362       unsigned ShAmt = Op->getConstantOperandVal(1);
12363       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12364         break;
12365       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12366                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12367                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12368       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12369         break;
12370       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12371                                 DAG.getConstant(Mask, VT));
12372       DAG.ReplaceAllUsesWith(Op, New);
12373       Op = New;
12374     }
12375     break;
12376
12377   case ISD::AND:
12378     // If the primary and result isn't used, don't bother using X86ISD::AND,
12379     // because a TEST instruction will be better.
12380     if (!hasNonFlagsUse(Op))
12381       break;
12382     // FALL THROUGH
12383   case ISD::SUB:
12384   case ISD::OR:
12385   case ISD::XOR:
12386     // Due to the ISEL shortcoming noted above, be conservative if this op is
12387     // likely to be selected as part of a load-modify-store instruction.
12388     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12389            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12390       if (UI->getOpcode() == ISD::STORE)
12391         goto default_case;
12392
12393     // Otherwise use a regular EFLAGS-setting instruction.
12394     switch (ArithOp.getOpcode()) {
12395     default: llvm_unreachable("unexpected operator!");
12396     case ISD::SUB: Opcode = X86ISD::SUB; break;
12397     case ISD::XOR: Opcode = X86ISD::XOR; break;
12398     case ISD::AND: Opcode = X86ISD::AND; break;
12399     case ISD::OR: {
12400       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12401         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12402         if (EFLAGS.getNode())
12403           return EFLAGS;
12404       }
12405       Opcode = X86ISD::OR;
12406       break;
12407     }
12408     }
12409
12410     NumOperands = 2;
12411     break;
12412   case X86ISD::ADD:
12413   case X86ISD::SUB:
12414   case X86ISD::INC:
12415   case X86ISD::DEC:
12416   case X86ISD::OR:
12417   case X86ISD::XOR:
12418   case X86ISD::AND:
12419     return SDValue(Op.getNode(), 1);
12420   default:
12421   default_case:
12422     break;
12423   }
12424
12425   // If we found that truncation is beneficial, perform the truncation and
12426   // update 'Op'.
12427   if (NeedTruncation) {
12428     EVT VT = Op.getValueType();
12429     SDValue WideVal = Op->getOperand(0);
12430     EVT WideVT = WideVal.getValueType();
12431     unsigned ConvertedOp = 0;
12432     // Use a target machine opcode to prevent further DAGCombine
12433     // optimizations that may separate the arithmetic operations
12434     // from the setcc node.
12435     switch (WideVal.getOpcode()) {
12436       default: break;
12437       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12438       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12439       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12440       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12441       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12442     }
12443
12444     if (ConvertedOp) {
12445       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12446       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12447         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12448         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12449         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12450       }
12451     }
12452   }
12453
12454   if (Opcode == 0)
12455     // Emit a CMP with 0, which is the TEST pattern.
12456     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12457                        DAG.getConstant(0, Op.getValueType()));
12458
12459   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12460   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12461
12462   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12463   DAG.ReplaceAllUsesWith(Op, New);
12464   return SDValue(New.getNode(), 1);
12465 }
12466
12467 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12468 /// equivalent.
12469 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12470                                    SDLoc dl, SelectionDAG &DAG) const {
12471   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12472     if (C->getAPIntValue() == 0)
12473       return EmitTest(Op0, X86CC, dl, DAG);
12474
12475      if (Op0.getValueType() == MVT::i1)
12476        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12477   }
12478
12479   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12480        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12481     // Do the comparison at i32 if it's smaller, besides the Atom case.
12482     // This avoids subregister aliasing issues. Keep the smaller reference
12483     // if we're optimizing for size, however, as that'll allow better folding
12484     // of memory operations.
12485     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12486         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12487             Attribute::MinSize) &&
12488         !Subtarget->isAtom()) {
12489       unsigned ExtendOp =
12490           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12491       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12492       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12493     }
12494     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12495     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12496     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12497                               Op0, Op1);
12498     return SDValue(Sub.getNode(), 1);
12499   }
12500   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12501 }
12502
12503 /// Convert a comparison if required by the subtarget.
12504 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12505                                                  SelectionDAG &DAG) const {
12506   // If the subtarget does not support the FUCOMI instruction, floating-point
12507   // comparisons have to be converted.
12508   if (Subtarget->hasCMov() ||
12509       Cmp.getOpcode() != X86ISD::CMP ||
12510       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12511       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12512     return Cmp;
12513
12514   // The instruction selector will select an FUCOM instruction instead of
12515   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12516   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12517   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12518   SDLoc dl(Cmp);
12519   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12520   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12521   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12522                             DAG.getConstant(8, MVT::i8));
12523   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12524   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12525 }
12526
12527 /// The minimum architected relative accuracy is 2^-12. We need one
12528 /// Newton-Raphson step to have a good float result (24 bits of precision).
12529 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12530                                             DAGCombinerInfo &DCI,
12531                                             unsigned &RefinementSteps,
12532                                             bool &UseOneConstNR) const {
12533   // FIXME: We should use instruction latency models to calculate the cost of
12534   // each potential sequence, but this is very hard to do reliably because
12535   // at least Intel's Core* chips have variable timing based on the number of
12536   // significant digits in the divisor and/or sqrt operand.
12537   if (!Subtarget->useSqrtEst())
12538     return SDValue();
12539
12540   EVT VT = Op.getValueType();
12541
12542   // SSE1 has rsqrtss and rsqrtps.
12543   // TODO: Add support for AVX512 (v16f32).
12544   // It is likely not profitable to do this for f64 because a double-precision
12545   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12546   // instructions: convert to single, rsqrtss, convert back to double, refine
12547   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12548   // along with FMA, this could be a throughput win.
12549   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12550       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12551     RefinementSteps = 1;
12552     UseOneConstNR = false;
12553     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12554   }
12555   return SDValue();
12556 }
12557
12558 /// The minimum architected relative accuracy is 2^-12. We need one
12559 /// Newton-Raphson step to have a good float result (24 bits of precision).
12560 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12561                                             DAGCombinerInfo &DCI,
12562                                             unsigned &RefinementSteps) const {
12563   // FIXME: We should use instruction latency models to calculate the cost of
12564   // each potential sequence, but this is very hard to do reliably because
12565   // at least Intel's Core* chips have variable timing based on the number of
12566   // significant digits in the divisor.
12567   if (!Subtarget->useReciprocalEst())
12568     return SDValue();
12569
12570   EVT VT = Op.getValueType();
12571
12572   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12573   // TODO: Add support for AVX512 (v16f32).
12574   // It is likely not profitable to do this for f64 because a double-precision
12575   // reciprocal estimate with refinement on x86 prior to FMA requires
12576   // 15 instructions: convert to single, rcpss, convert back to double, refine
12577   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12578   // along with FMA, this could be a throughput win.
12579   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12580       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12581     RefinementSteps = ReciprocalEstimateRefinementSteps;
12582     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12583   }
12584   return SDValue();
12585 }
12586
12587 static bool isAllOnes(SDValue V) {
12588   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12589   return C && C->isAllOnesValue();
12590 }
12591
12592 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12593 /// if it's possible.
12594 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12595                                      SDLoc dl, SelectionDAG &DAG) const {
12596   SDValue Op0 = And.getOperand(0);
12597   SDValue Op1 = And.getOperand(1);
12598   if (Op0.getOpcode() == ISD::TRUNCATE)
12599     Op0 = Op0.getOperand(0);
12600   if (Op1.getOpcode() == ISD::TRUNCATE)
12601     Op1 = Op1.getOperand(0);
12602
12603   SDValue LHS, RHS;
12604   if (Op1.getOpcode() == ISD::SHL)
12605     std::swap(Op0, Op1);
12606   if (Op0.getOpcode() == ISD::SHL) {
12607     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12608       if (And00C->getZExtValue() == 1) {
12609         // If we looked past a truncate, check that it's only truncating away
12610         // known zeros.
12611         unsigned BitWidth = Op0.getValueSizeInBits();
12612         unsigned AndBitWidth = And.getValueSizeInBits();
12613         if (BitWidth > AndBitWidth) {
12614           APInt Zeros, Ones;
12615           DAG.computeKnownBits(Op0, Zeros, Ones);
12616           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12617             return SDValue();
12618         }
12619         LHS = Op1;
12620         RHS = Op0.getOperand(1);
12621       }
12622   } else if (Op1.getOpcode() == ISD::Constant) {
12623     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12624     uint64_t AndRHSVal = AndRHS->getZExtValue();
12625     SDValue AndLHS = Op0;
12626
12627     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12628       LHS = AndLHS.getOperand(0);
12629       RHS = AndLHS.getOperand(1);
12630     }
12631
12632     // Use BT if the immediate can't be encoded in a TEST instruction.
12633     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12634       LHS = AndLHS;
12635       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12636     }
12637   }
12638
12639   if (LHS.getNode()) {
12640     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12641     // instruction.  Since the shift amount is in-range-or-undefined, we know
12642     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12643     // the encoding for the i16 version is larger than the i32 version.
12644     // Also promote i16 to i32 for performance / code size reason.
12645     if (LHS.getValueType() == MVT::i8 ||
12646         LHS.getValueType() == MVT::i16)
12647       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12648
12649     // If the operand types disagree, extend the shift amount to match.  Since
12650     // BT ignores high bits (like shifts) we can use anyextend.
12651     if (LHS.getValueType() != RHS.getValueType())
12652       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12653
12654     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12655     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12656     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12657                        DAG.getConstant(Cond, MVT::i8), BT);
12658   }
12659
12660   return SDValue();
12661 }
12662
12663 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12664 /// mask CMPs.
12665 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12666                               SDValue &Op1) {
12667   unsigned SSECC;
12668   bool Swap = false;
12669
12670   // SSE Condition code mapping:
12671   //  0 - EQ
12672   //  1 - LT
12673   //  2 - LE
12674   //  3 - UNORD
12675   //  4 - NEQ
12676   //  5 - NLT
12677   //  6 - NLE
12678   //  7 - ORD
12679   switch (SetCCOpcode) {
12680   default: llvm_unreachable("Unexpected SETCC condition");
12681   case ISD::SETOEQ:
12682   case ISD::SETEQ:  SSECC = 0; break;
12683   case ISD::SETOGT:
12684   case ISD::SETGT:  Swap = true; // Fallthrough
12685   case ISD::SETLT:
12686   case ISD::SETOLT: SSECC = 1; break;
12687   case ISD::SETOGE:
12688   case ISD::SETGE:  Swap = true; // Fallthrough
12689   case ISD::SETLE:
12690   case ISD::SETOLE: SSECC = 2; break;
12691   case ISD::SETUO:  SSECC = 3; break;
12692   case ISD::SETUNE:
12693   case ISD::SETNE:  SSECC = 4; break;
12694   case ISD::SETULE: Swap = true; // Fallthrough
12695   case ISD::SETUGE: SSECC = 5; break;
12696   case ISD::SETULT: Swap = true; // Fallthrough
12697   case ISD::SETUGT: SSECC = 6; break;
12698   case ISD::SETO:   SSECC = 7; break;
12699   case ISD::SETUEQ:
12700   case ISD::SETONE: SSECC = 8; break;
12701   }
12702   if (Swap)
12703     std::swap(Op0, Op1);
12704
12705   return SSECC;
12706 }
12707
12708 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12709 // ones, and then concatenate the result back.
12710 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12711   MVT VT = Op.getSimpleValueType();
12712
12713   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12714          "Unsupported value type for operation");
12715
12716   unsigned NumElems = VT.getVectorNumElements();
12717   SDLoc dl(Op);
12718   SDValue CC = Op.getOperand(2);
12719
12720   // Extract the LHS vectors
12721   SDValue LHS = Op.getOperand(0);
12722   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12723   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12724
12725   // Extract the RHS vectors
12726   SDValue RHS = Op.getOperand(1);
12727   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12728   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12729
12730   // Issue the operation on the smaller types and concatenate the result back
12731   MVT EltVT = VT.getVectorElementType();
12732   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12733   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12734                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12735                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12736 }
12737
12738 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12739                                      const X86Subtarget *Subtarget) {
12740   SDValue Op0 = Op.getOperand(0);
12741   SDValue Op1 = Op.getOperand(1);
12742   SDValue CC = Op.getOperand(2);
12743   MVT VT = Op.getSimpleValueType();
12744   SDLoc dl(Op);
12745
12746   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12747          Op.getValueType().getScalarType() == MVT::i1 &&
12748          "Cannot set masked compare for this operation");
12749
12750   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12751   unsigned  Opc = 0;
12752   bool Unsigned = false;
12753   bool Swap = false;
12754   unsigned SSECC;
12755   switch (SetCCOpcode) {
12756   default: llvm_unreachable("Unexpected SETCC condition");
12757   case ISD::SETNE:  SSECC = 4; break;
12758   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12759   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12760   case ISD::SETLT:  Swap = true; //fall-through
12761   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12762   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12763   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12764   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12765   case ISD::SETULE: Unsigned = true; //fall-through
12766   case ISD::SETLE:  SSECC = 2; break;
12767   }
12768
12769   if (Swap)
12770     std::swap(Op0, Op1);
12771   if (Opc)
12772     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12773   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12774   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12775                      DAG.getConstant(SSECC, MVT::i8));
12776 }
12777
12778 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12779 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12780 /// return an empty value.
12781 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12782 {
12783   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12784   if (!BV)
12785     return SDValue();
12786
12787   MVT VT = Op1.getSimpleValueType();
12788   MVT EVT = VT.getVectorElementType();
12789   unsigned n = VT.getVectorNumElements();
12790   SmallVector<SDValue, 8> ULTOp1;
12791
12792   for (unsigned i = 0; i < n; ++i) {
12793     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12794     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12795       return SDValue();
12796
12797     // Avoid underflow.
12798     APInt Val = Elt->getAPIntValue();
12799     if (Val == 0)
12800       return SDValue();
12801
12802     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12803   }
12804
12805   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12806 }
12807
12808 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12809                            SelectionDAG &DAG) {
12810   SDValue Op0 = Op.getOperand(0);
12811   SDValue Op1 = Op.getOperand(1);
12812   SDValue CC = Op.getOperand(2);
12813   MVT VT = Op.getSimpleValueType();
12814   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12815   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12816   SDLoc dl(Op);
12817
12818   if (isFP) {
12819 #ifndef NDEBUG
12820     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12821     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12822 #endif
12823
12824     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12825     unsigned Opc = X86ISD::CMPP;
12826     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12827       assert(VT.getVectorNumElements() <= 16);
12828       Opc = X86ISD::CMPM;
12829     }
12830     // In the two special cases we can't handle, emit two comparisons.
12831     if (SSECC == 8) {
12832       unsigned CC0, CC1;
12833       unsigned CombineOpc;
12834       if (SetCCOpcode == ISD::SETUEQ) {
12835         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12836       } else {
12837         assert(SetCCOpcode == ISD::SETONE);
12838         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12839       }
12840
12841       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12842                                  DAG.getConstant(CC0, MVT::i8));
12843       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12844                                  DAG.getConstant(CC1, MVT::i8));
12845       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12846     }
12847     // Handle all other FP comparisons here.
12848     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12849                        DAG.getConstant(SSECC, MVT::i8));
12850   }
12851
12852   // Break 256-bit integer vector compare into smaller ones.
12853   if (VT.is256BitVector() && !Subtarget->hasInt256())
12854     return Lower256IntVSETCC(Op, DAG);
12855
12856   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12857   EVT OpVT = Op1.getValueType();
12858   if (Subtarget->hasAVX512()) {
12859     if (Op1.getValueType().is512BitVector() ||
12860         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
12861         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12862       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12863
12864     // In AVX-512 architecture setcc returns mask with i1 elements,
12865     // But there is no compare instruction for i8 and i16 elements in KNL.
12866     // We are not talking about 512-bit operands in this case, these
12867     // types are illegal.
12868     if (MaskResult &&
12869         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12870          OpVT.getVectorElementType().getSizeInBits() >= 8))
12871       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12872                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12873   }
12874
12875   // We are handling one of the integer comparisons here.  Since SSE only has
12876   // GT and EQ comparisons for integer, swapping operands and multiple
12877   // operations may be required for some comparisons.
12878   unsigned Opc;
12879   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12880   bool Subus = false;
12881
12882   switch (SetCCOpcode) {
12883   default: llvm_unreachable("Unexpected SETCC condition");
12884   case ISD::SETNE:  Invert = true;
12885   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12886   case ISD::SETLT:  Swap = true;
12887   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12888   case ISD::SETGE:  Swap = true;
12889   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12890                     Invert = true; break;
12891   case ISD::SETULT: Swap = true;
12892   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12893                     FlipSigns = true; break;
12894   case ISD::SETUGE: Swap = true;
12895   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12896                     FlipSigns = true; Invert = true; break;
12897   }
12898
12899   // Special case: Use min/max operations for SETULE/SETUGE
12900   MVT VET = VT.getVectorElementType();
12901   bool hasMinMax =
12902        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12903     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12904
12905   if (hasMinMax) {
12906     switch (SetCCOpcode) {
12907     default: break;
12908     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12909     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12910     }
12911
12912     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12913   }
12914
12915   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12916   if (!MinMax && hasSubus) {
12917     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12918     // Op0 u<= Op1:
12919     //   t = psubus Op0, Op1
12920     //   pcmpeq t, <0..0>
12921     switch (SetCCOpcode) {
12922     default: break;
12923     case ISD::SETULT: {
12924       // If the comparison is against a constant we can turn this into a
12925       // setule.  With psubus, setule does not require a swap.  This is
12926       // beneficial because the constant in the register is no longer
12927       // destructed as the destination so it can be hoisted out of a loop.
12928       // Only do this pre-AVX since vpcmp* is no longer destructive.
12929       if (Subtarget->hasAVX())
12930         break;
12931       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12932       if (ULEOp1.getNode()) {
12933         Op1 = ULEOp1;
12934         Subus = true; Invert = false; Swap = false;
12935       }
12936       break;
12937     }
12938     // Psubus is better than flip-sign because it requires no inversion.
12939     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12940     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12941     }
12942
12943     if (Subus) {
12944       Opc = X86ISD::SUBUS;
12945       FlipSigns = false;
12946     }
12947   }
12948
12949   if (Swap)
12950     std::swap(Op0, Op1);
12951
12952   // Check that the operation in question is available (most are plain SSE2,
12953   // but PCMPGTQ and PCMPEQQ have different requirements).
12954   if (VT == MVT::v2i64) {
12955     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12956       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12957
12958       // First cast everything to the right type.
12959       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12960       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12961
12962       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12963       // bits of the inputs before performing those operations. The lower
12964       // compare is always unsigned.
12965       SDValue SB;
12966       if (FlipSigns) {
12967         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12968       } else {
12969         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12970         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12971         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12972                          Sign, Zero, Sign, Zero);
12973       }
12974       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12975       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12976
12977       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12978       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12979       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12980
12981       // Create masks for only the low parts/high parts of the 64 bit integers.
12982       static const int MaskHi[] = { 1, 1, 3, 3 };
12983       static const int MaskLo[] = { 0, 0, 2, 2 };
12984       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12985       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12986       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12987
12988       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12989       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12990
12991       if (Invert)
12992         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12993
12994       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12995     }
12996
12997     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12998       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12999       // pcmpeqd + pshufd + pand.
13000       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13001
13002       // First cast everything to the right type.
13003       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13004       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13005
13006       // Do the compare.
13007       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13008
13009       // Make sure the lower and upper halves are both all-ones.
13010       static const int Mask[] = { 1, 0, 3, 2 };
13011       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13012       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13013
13014       if (Invert)
13015         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13016
13017       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13018     }
13019   }
13020
13021   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13022   // bits of the inputs before performing those operations.
13023   if (FlipSigns) {
13024     EVT EltVT = VT.getVectorElementType();
13025     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13026     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13027     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13028   }
13029
13030   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13031
13032   // If the logical-not of the result is required, perform that now.
13033   if (Invert)
13034     Result = DAG.getNOT(dl, Result, VT);
13035
13036   if (MinMax)
13037     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13038
13039   if (Subus)
13040     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13041                          getZeroVector(VT, Subtarget, DAG, dl));
13042
13043   return Result;
13044 }
13045
13046 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13047
13048   MVT VT = Op.getSimpleValueType();
13049
13050   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13051
13052   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13053          && "SetCC type must be 8-bit or 1-bit integer");
13054   SDValue Op0 = Op.getOperand(0);
13055   SDValue Op1 = Op.getOperand(1);
13056   SDLoc dl(Op);
13057   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13058
13059   // Optimize to BT if possible.
13060   // Lower (X & (1 << N)) == 0 to BT(X, N).
13061   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13062   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13063   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13064       Op1.getOpcode() == ISD::Constant &&
13065       cast<ConstantSDNode>(Op1)->isNullValue() &&
13066       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13067     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13068     if (NewSetCC.getNode()) {
13069       if (VT == MVT::i1)
13070         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13071       return NewSetCC;
13072     }
13073   }
13074
13075   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13076   // these.
13077   if (Op1.getOpcode() == ISD::Constant &&
13078       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13079        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13080       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13081
13082     // If the input is a setcc, then reuse the input setcc or use a new one with
13083     // the inverted condition.
13084     if (Op0.getOpcode() == X86ISD::SETCC) {
13085       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13086       bool Invert = (CC == ISD::SETNE) ^
13087         cast<ConstantSDNode>(Op1)->isNullValue();
13088       if (!Invert)
13089         return Op0;
13090
13091       CCode = X86::GetOppositeBranchCondition(CCode);
13092       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13093                                   DAG.getConstant(CCode, MVT::i8),
13094                                   Op0.getOperand(1));
13095       if (VT == MVT::i1)
13096         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13097       return SetCC;
13098     }
13099   }
13100   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13101       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13102       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13103
13104     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13105     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13106   }
13107
13108   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13109   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13110   if (X86CC == X86::COND_INVALID)
13111     return SDValue();
13112
13113   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13114   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13115   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13116                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13117   if (VT == MVT::i1)
13118     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13119   return SetCC;
13120 }
13121
13122 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13123 static bool isX86LogicalCmp(SDValue Op) {
13124   unsigned Opc = Op.getNode()->getOpcode();
13125   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13126       Opc == X86ISD::SAHF)
13127     return true;
13128   if (Op.getResNo() == 1 &&
13129       (Opc == X86ISD::ADD ||
13130        Opc == X86ISD::SUB ||
13131        Opc == X86ISD::ADC ||
13132        Opc == X86ISD::SBB ||
13133        Opc == X86ISD::SMUL ||
13134        Opc == X86ISD::UMUL ||
13135        Opc == X86ISD::INC ||
13136        Opc == X86ISD::DEC ||
13137        Opc == X86ISD::OR ||
13138        Opc == X86ISD::XOR ||
13139        Opc == X86ISD::AND))
13140     return true;
13141
13142   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13143     return true;
13144
13145   return false;
13146 }
13147
13148 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13149   if (V.getOpcode() != ISD::TRUNCATE)
13150     return false;
13151
13152   SDValue VOp0 = V.getOperand(0);
13153   unsigned InBits = VOp0.getValueSizeInBits();
13154   unsigned Bits = V.getValueSizeInBits();
13155   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13156 }
13157
13158 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13159   bool addTest = true;
13160   SDValue Cond  = Op.getOperand(0);
13161   SDValue Op1 = Op.getOperand(1);
13162   SDValue Op2 = Op.getOperand(2);
13163   SDLoc DL(Op);
13164   EVT VT = Op1.getValueType();
13165   SDValue CC;
13166
13167   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13168   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13169   // sequence later on.
13170   if (Cond.getOpcode() == ISD::SETCC &&
13171       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13172        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13173       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13174     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13175     int SSECC = translateX86FSETCC(
13176         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13177
13178     if (SSECC != 8) {
13179       if (Subtarget->hasAVX512()) {
13180         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13181                                   DAG.getConstant(SSECC, MVT::i8));
13182         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13183       }
13184       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13185                                 DAG.getConstant(SSECC, MVT::i8));
13186       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13187       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13188       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13189     }
13190   }
13191
13192   if (Cond.getOpcode() == ISD::SETCC) {
13193     SDValue NewCond = LowerSETCC(Cond, DAG);
13194     if (NewCond.getNode())
13195       Cond = NewCond;
13196   }
13197
13198   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13199   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13200   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13201   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13202   if (Cond.getOpcode() == X86ISD::SETCC &&
13203       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13204       isZero(Cond.getOperand(1).getOperand(1))) {
13205     SDValue Cmp = Cond.getOperand(1);
13206
13207     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13208
13209     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13210         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13211       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13212
13213       SDValue CmpOp0 = Cmp.getOperand(0);
13214       // Apply further optimizations for special cases
13215       // (select (x != 0), -1, 0) -> neg & sbb
13216       // (select (x == 0), 0, -1) -> neg & sbb
13217       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13218         if (YC->isNullValue() &&
13219             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13220           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13221           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13222                                     DAG.getConstant(0, CmpOp0.getValueType()),
13223                                     CmpOp0);
13224           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13225                                     DAG.getConstant(X86::COND_B, MVT::i8),
13226                                     SDValue(Neg.getNode(), 1));
13227           return Res;
13228         }
13229
13230       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13231                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13232       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13233
13234       SDValue Res =   // Res = 0 or -1.
13235         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13236                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13237
13238       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13239         Res = DAG.getNOT(DL, Res, Res.getValueType());
13240
13241       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13242       if (!N2C || !N2C->isNullValue())
13243         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13244       return Res;
13245     }
13246   }
13247
13248   // Look past (and (setcc_carry (cmp ...)), 1).
13249   if (Cond.getOpcode() == ISD::AND &&
13250       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13251     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13252     if (C && C->getAPIntValue() == 1)
13253       Cond = Cond.getOperand(0);
13254   }
13255
13256   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13257   // setting operand in place of the X86ISD::SETCC.
13258   unsigned CondOpcode = Cond.getOpcode();
13259   if (CondOpcode == X86ISD::SETCC ||
13260       CondOpcode == X86ISD::SETCC_CARRY) {
13261     CC = Cond.getOperand(0);
13262
13263     SDValue Cmp = Cond.getOperand(1);
13264     unsigned Opc = Cmp.getOpcode();
13265     MVT VT = Op.getSimpleValueType();
13266
13267     bool IllegalFPCMov = false;
13268     if (VT.isFloatingPoint() && !VT.isVector() &&
13269         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13270       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13271
13272     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13273         Opc == X86ISD::BT) { // FIXME
13274       Cond = Cmp;
13275       addTest = false;
13276     }
13277   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13278              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13279              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13280               Cond.getOperand(0).getValueType() != MVT::i8)) {
13281     SDValue LHS = Cond.getOperand(0);
13282     SDValue RHS = Cond.getOperand(1);
13283     unsigned X86Opcode;
13284     unsigned X86Cond;
13285     SDVTList VTs;
13286     switch (CondOpcode) {
13287     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13288     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13289     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13290     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13291     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13292     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13293     default: llvm_unreachable("unexpected overflowing operator");
13294     }
13295     if (CondOpcode == ISD::UMULO)
13296       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13297                           MVT::i32);
13298     else
13299       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13300
13301     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13302
13303     if (CondOpcode == ISD::UMULO)
13304       Cond = X86Op.getValue(2);
13305     else
13306       Cond = X86Op.getValue(1);
13307
13308     CC = DAG.getConstant(X86Cond, MVT::i8);
13309     addTest = false;
13310   }
13311
13312   if (addTest) {
13313     // Look pass the truncate if the high bits are known zero.
13314     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13315         Cond = Cond.getOperand(0);
13316
13317     // We know the result of AND is compared against zero. Try to match
13318     // it to BT.
13319     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13320       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13321       if (NewSetCC.getNode()) {
13322         CC = NewSetCC.getOperand(0);
13323         Cond = NewSetCC.getOperand(1);
13324         addTest = false;
13325       }
13326     }
13327   }
13328
13329   if (addTest) {
13330     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13331     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13332   }
13333
13334   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13335   // a <  b ?  0 : -1 -> RES = setcc_carry
13336   // a >= b ? -1 :  0 -> RES = setcc_carry
13337   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13338   if (Cond.getOpcode() == X86ISD::SUB) {
13339     Cond = ConvertCmpIfNecessary(Cond, DAG);
13340     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13341
13342     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13343         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13344       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13345                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13346       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13347         return DAG.getNOT(DL, Res, Res.getValueType());
13348       return Res;
13349     }
13350   }
13351
13352   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13353   // widen the cmov and push the truncate through. This avoids introducing a new
13354   // branch during isel and doesn't add any extensions.
13355   if (Op.getValueType() == MVT::i8 &&
13356       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13357     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13358     if (T1.getValueType() == T2.getValueType() &&
13359         // Blacklist CopyFromReg to avoid partial register stalls.
13360         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13361       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13362       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13363       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13364     }
13365   }
13366
13367   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13368   // condition is true.
13369   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13370   SDValue Ops[] = { Op2, Op1, CC, Cond };
13371   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13372 }
13373
13374 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13375                                        SelectionDAG &DAG) {
13376   MVT VT = Op->getSimpleValueType(0);
13377   SDValue In = Op->getOperand(0);
13378   MVT InVT = In.getSimpleValueType();
13379   MVT VTElt = VT.getVectorElementType();
13380   MVT InVTElt = InVT.getVectorElementType();
13381   SDLoc dl(Op);
13382
13383   // SKX processor
13384   if ((InVTElt == MVT::i1) &&
13385       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13386         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13387
13388        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13389         VTElt.getSizeInBits() <= 16)) ||
13390
13391        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13392         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13393
13394        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13395         VTElt.getSizeInBits() >= 32))))
13396     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13397
13398   unsigned int NumElts = VT.getVectorNumElements();
13399
13400   if (NumElts != 8 && NumElts != 16)
13401     return SDValue();
13402
13403   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13404     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13405       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13406     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13407   }
13408
13409   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13410   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13411
13412   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13413   Constant *C = ConstantInt::get(*DAG.getContext(),
13414     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13415
13416   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13417   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13418   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13419                           MachinePointerInfo::getConstantPool(),
13420                           false, false, false, Alignment);
13421   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13422   if (VT.is512BitVector())
13423     return Brcst;
13424   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13425 }
13426
13427 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13428                                 SelectionDAG &DAG) {
13429   MVT VT = Op->getSimpleValueType(0);
13430   SDValue In = Op->getOperand(0);
13431   MVT InVT = In.getSimpleValueType();
13432   SDLoc dl(Op);
13433
13434   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13435     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13436
13437   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13438       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13439       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13440     return SDValue();
13441
13442   if (Subtarget->hasInt256())
13443     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13444
13445   // Optimize vectors in AVX mode
13446   // Sign extend  v8i16 to v8i32 and
13447   //              v4i32 to v4i64
13448   //
13449   // Divide input vector into two parts
13450   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13451   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13452   // concat the vectors to original VT
13453
13454   unsigned NumElems = InVT.getVectorNumElements();
13455   SDValue Undef = DAG.getUNDEF(InVT);
13456
13457   SmallVector<int,8> ShufMask1(NumElems, -1);
13458   for (unsigned i = 0; i != NumElems/2; ++i)
13459     ShufMask1[i] = i;
13460
13461   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13462
13463   SmallVector<int,8> ShufMask2(NumElems, -1);
13464   for (unsigned i = 0; i != NumElems/2; ++i)
13465     ShufMask2[i] = i + NumElems/2;
13466
13467   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13468
13469   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13470                                 VT.getVectorNumElements()/2);
13471
13472   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13473   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13474
13475   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13476 }
13477
13478 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13479 // may emit an illegal shuffle but the expansion is still better than scalar
13480 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13481 // we'll emit a shuffle and a arithmetic shift.
13482 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13483 // TODO: It is possible to support ZExt by zeroing the undef values during
13484 // the shuffle phase or after the shuffle.
13485 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13486                                  SelectionDAG &DAG) {
13487   MVT RegVT = Op.getSimpleValueType();
13488   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13489   assert(RegVT.isInteger() &&
13490          "We only custom lower integer vector sext loads.");
13491
13492   // Nothing useful we can do without SSE2 shuffles.
13493   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13494
13495   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13496   SDLoc dl(Ld);
13497   EVT MemVT = Ld->getMemoryVT();
13498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13499   unsigned RegSz = RegVT.getSizeInBits();
13500
13501   ISD::LoadExtType Ext = Ld->getExtensionType();
13502
13503   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13504          && "Only anyext and sext are currently implemented.");
13505   assert(MemVT != RegVT && "Cannot extend to the same type");
13506   assert(MemVT.isVector() && "Must load a vector from memory");
13507
13508   unsigned NumElems = RegVT.getVectorNumElements();
13509   unsigned MemSz = MemVT.getSizeInBits();
13510   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13511
13512   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13513     // The only way in which we have a legal 256-bit vector result but not the
13514     // integer 256-bit operations needed to directly lower a sextload is if we
13515     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13516     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13517     // correctly legalized. We do this late to allow the canonical form of
13518     // sextload to persist throughout the rest of the DAG combiner -- it wants
13519     // to fold together any extensions it can, and so will fuse a sign_extend
13520     // of an sextload into a sextload targeting a wider value.
13521     SDValue Load;
13522     if (MemSz == 128) {
13523       // Just switch this to a normal load.
13524       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13525                                        "it must be a legal 128-bit vector "
13526                                        "type!");
13527       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13528                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13529                   Ld->isInvariant(), Ld->getAlignment());
13530     } else {
13531       assert(MemSz < 128 &&
13532              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13533       // Do an sext load to a 128-bit vector type. We want to use the same
13534       // number of elements, but elements half as wide. This will end up being
13535       // recursively lowered by this routine, but will succeed as we definitely
13536       // have all the necessary features if we're using AVX1.
13537       EVT HalfEltVT =
13538           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13539       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13540       Load =
13541           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13542                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13543                          Ld->isNonTemporal(), Ld->isInvariant(),
13544                          Ld->getAlignment());
13545     }
13546
13547     // Replace chain users with the new chain.
13548     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13549     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13550
13551     // Finally, do a normal sign-extend to the desired register.
13552     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13553   }
13554
13555   // All sizes must be a power of two.
13556   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13557          "Non-power-of-two elements are not custom lowered!");
13558
13559   // Attempt to load the original value using scalar loads.
13560   // Find the largest scalar type that divides the total loaded size.
13561   MVT SclrLoadTy = MVT::i8;
13562   for (MVT Tp : MVT::integer_valuetypes()) {
13563     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13564       SclrLoadTy = Tp;
13565     }
13566   }
13567
13568   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13569   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13570       (64 <= MemSz))
13571     SclrLoadTy = MVT::f64;
13572
13573   // Calculate the number of scalar loads that we need to perform
13574   // in order to load our vector from memory.
13575   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13576
13577   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13578          "Can only lower sext loads with a single scalar load!");
13579
13580   unsigned loadRegZize = RegSz;
13581   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13582     loadRegZize /= 2;
13583
13584   // Represent our vector as a sequence of elements which are the
13585   // largest scalar that we can load.
13586   EVT LoadUnitVecVT = EVT::getVectorVT(
13587       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13588
13589   // Represent the data using the same element type that is stored in
13590   // memory. In practice, we ''widen'' MemVT.
13591   EVT WideVecVT =
13592       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13593                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13594
13595   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13596          "Invalid vector type");
13597
13598   // We can't shuffle using an illegal type.
13599   assert(TLI.isTypeLegal(WideVecVT) &&
13600          "We only lower types that form legal widened vector types");
13601
13602   SmallVector<SDValue, 8> Chains;
13603   SDValue Ptr = Ld->getBasePtr();
13604   SDValue Increment =
13605       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13606   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13607
13608   for (unsigned i = 0; i < NumLoads; ++i) {
13609     // Perform a single load.
13610     SDValue ScalarLoad =
13611         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13612                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13613                     Ld->getAlignment());
13614     Chains.push_back(ScalarLoad.getValue(1));
13615     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13616     // another round of DAGCombining.
13617     if (i == 0)
13618       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13619     else
13620       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13621                         ScalarLoad, DAG.getIntPtrConstant(i));
13622
13623     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13624   }
13625
13626   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13627
13628   // Bitcast the loaded value to a vector of the original element type, in
13629   // the size of the target vector type.
13630   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13631   unsigned SizeRatio = RegSz / MemSz;
13632
13633   if (Ext == ISD::SEXTLOAD) {
13634     // If we have SSE4.1, we can directly emit a VSEXT node.
13635     if (Subtarget->hasSSE41()) {
13636       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13637       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13638       return Sext;
13639     }
13640
13641     // Otherwise we'll shuffle the small elements in the high bits of the
13642     // larger type and perform an arithmetic shift. If the shift is not legal
13643     // it's better to scalarize.
13644     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13645            "We can't implement a sext load without an arithmetic right shift!");
13646
13647     // Redistribute the loaded elements into the different locations.
13648     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13649     for (unsigned i = 0; i != NumElems; ++i)
13650       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13651
13652     SDValue Shuff = DAG.getVectorShuffle(
13653         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13654
13655     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13656
13657     // Build the arithmetic shift.
13658     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13659                    MemVT.getVectorElementType().getSizeInBits();
13660     Shuff =
13661         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13662
13663     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13664     return Shuff;
13665   }
13666
13667   // Redistribute the loaded elements into the different locations.
13668   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13669   for (unsigned i = 0; i != NumElems; ++i)
13670     ShuffleVec[i * SizeRatio] = i;
13671
13672   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13673                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13674
13675   // Bitcast to the requested type.
13676   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13677   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13678   return Shuff;
13679 }
13680
13681 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13682 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13683 // from the AND / OR.
13684 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13685   Opc = Op.getOpcode();
13686   if (Opc != ISD::OR && Opc != ISD::AND)
13687     return false;
13688   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13689           Op.getOperand(0).hasOneUse() &&
13690           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13691           Op.getOperand(1).hasOneUse());
13692 }
13693
13694 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13695 // 1 and that the SETCC node has a single use.
13696 static bool isXor1OfSetCC(SDValue Op) {
13697   if (Op.getOpcode() != ISD::XOR)
13698     return false;
13699   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13700   if (N1C && N1C->getAPIntValue() == 1) {
13701     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13702       Op.getOperand(0).hasOneUse();
13703   }
13704   return false;
13705 }
13706
13707 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13708   bool addTest = true;
13709   SDValue Chain = Op.getOperand(0);
13710   SDValue Cond  = Op.getOperand(1);
13711   SDValue Dest  = Op.getOperand(2);
13712   SDLoc dl(Op);
13713   SDValue CC;
13714   bool Inverted = false;
13715
13716   if (Cond.getOpcode() == ISD::SETCC) {
13717     // Check for setcc([su]{add,sub,mul}o == 0).
13718     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13719         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13720         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13721         Cond.getOperand(0).getResNo() == 1 &&
13722         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13723          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13724          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13725          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13726          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13727          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13728       Inverted = true;
13729       Cond = Cond.getOperand(0);
13730     } else {
13731       SDValue NewCond = LowerSETCC(Cond, DAG);
13732       if (NewCond.getNode())
13733         Cond = NewCond;
13734     }
13735   }
13736 #if 0
13737   // FIXME: LowerXALUO doesn't handle these!!
13738   else if (Cond.getOpcode() == X86ISD::ADD  ||
13739            Cond.getOpcode() == X86ISD::SUB  ||
13740            Cond.getOpcode() == X86ISD::SMUL ||
13741            Cond.getOpcode() == X86ISD::UMUL)
13742     Cond = LowerXALUO(Cond, DAG);
13743 #endif
13744
13745   // Look pass (and (setcc_carry (cmp ...)), 1).
13746   if (Cond.getOpcode() == ISD::AND &&
13747       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13748     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13749     if (C && C->getAPIntValue() == 1)
13750       Cond = Cond.getOperand(0);
13751   }
13752
13753   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13754   // setting operand in place of the X86ISD::SETCC.
13755   unsigned CondOpcode = Cond.getOpcode();
13756   if (CondOpcode == X86ISD::SETCC ||
13757       CondOpcode == X86ISD::SETCC_CARRY) {
13758     CC = Cond.getOperand(0);
13759
13760     SDValue Cmp = Cond.getOperand(1);
13761     unsigned Opc = Cmp.getOpcode();
13762     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13763     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13764       Cond = Cmp;
13765       addTest = false;
13766     } else {
13767       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13768       default: break;
13769       case X86::COND_O:
13770       case X86::COND_B:
13771         // These can only come from an arithmetic instruction with overflow,
13772         // e.g. SADDO, UADDO.
13773         Cond = Cond.getNode()->getOperand(1);
13774         addTest = false;
13775         break;
13776       }
13777     }
13778   }
13779   CondOpcode = Cond.getOpcode();
13780   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13781       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13782       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13783        Cond.getOperand(0).getValueType() != MVT::i8)) {
13784     SDValue LHS = Cond.getOperand(0);
13785     SDValue RHS = Cond.getOperand(1);
13786     unsigned X86Opcode;
13787     unsigned X86Cond;
13788     SDVTList VTs;
13789     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13790     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13791     // X86ISD::INC).
13792     switch (CondOpcode) {
13793     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13794     case ISD::SADDO:
13795       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13796         if (C->isOne()) {
13797           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13798           break;
13799         }
13800       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13801     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13802     case ISD::SSUBO:
13803       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13804         if (C->isOne()) {
13805           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13806           break;
13807         }
13808       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13809     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13810     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13811     default: llvm_unreachable("unexpected overflowing operator");
13812     }
13813     if (Inverted)
13814       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13815     if (CondOpcode == ISD::UMULO)
13816       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13817                           MVT::i32);
13818     else
13819       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13820
13821     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13822
13823     if (CondOpcode == ISD::UMULO)
13824       Cond = X86Op.getValue(2);
13825     else
13826       Cond = X86Op.getValue(1);
13827
13828     CC = DAG.getConstant(X86Cond, MVT::i8);
13829     addTest = false;
13830   } else {
13831     unsigned CondOpc;
13832     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13833       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13834       if (CondOpc == ISD::OR) {
13835         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13836         // two branches instead of an explicit OR instruction with a
13837         // separate test.
13838         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13839             isX86LogicalCmp(Cmp)) {
13840           CC = Cond.getOperand(0).getOperand(0);
13841           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13842                               Chain, Dest, CC, Cmp);
13843           CC = Cond.getOperand(1).getOperand(0);
13844           Cond = Cmp;
13845           addTest = false;
13846         }
13847       } else { // ISD::AND
13848         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13849         // two branches instead of an explicit AND instruction with a
13850         // separate test. However, we only do this if this block doesn't
13851         // have a fall-through edge, because this requires an explicit
13852         // jmp when the condition is false.
13853         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13854             isX86LogicalCmp(Cmp) &&
13855             Op.getNode()->hasOneUse()) {
13856           X86::CondCode CCode =
13857             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13858           CCode = X86::GetOppositeBranchCondition(CCode);
13859           CC = DAG.getConstant(CCode, MVT::i8);
13860           SDNode *User = *Op.getNode()->use_begin();
13861           // Look for an unconditional branch following this conditional branch.
13862           // We need this because we need to reverse the successors in order
13863           // to implement FCMP_OEQ.
13864           if (User->getOpcode() == ISD::BR) {
13865             SDValue FalseBB = User->getOperand(1);
13866             SDNode *NewBR =
13867               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13868             assert(NewBR == User);
13869             (void)NewBR;
13870             Dest = FalseBB;
13871
13872             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13873                                 Chain, Dest, CC, Cmp);
13874             X86::CondCode CCode =
13875               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13876             CCode = X86::GetOppositeBranchCondition(CCode);
13877             CC = DAG.getConstant(CCode, MVT::i8);
13878             Cond = Cmp;
13879             addTest = false;
13880           }
13881         }
13882       }
13883     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13884       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13885       // It should be transformed during dag combiner except when the condition
13886       // is set by a arithmetics with overflow node.
13887       X86::CondCode CCode =
13888         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13889       CCode = X86::GetOppositeBranchCondition(CCode);
13890       CC = DAG.getConstant(CCode, MVT::i8);
13891       Cond = Cond.getOperand(0).getOperand(1);
13892       addTest = false;
13893     } else if (Cond.getOpcode() == ISD::SETCC &&
13894                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13895       // For FCMP_OEQ, we can emit
13896       // two branches instead of an explicit AND instruction with a
13897       // separate test. However, we only do this if this block doesn't
13898       // have a fall-through edge, because this requires an explicit
13899       // jmp when the condition is false.
13900       if (Op.getNode()->hasOneUse()) {
13901         SDNode *User = *Op.getNode()->use_begin();
13902         // Look for an unconditional branch following this conditional branch.
13903         // We need this because we need to reverse the successors in order
13904         // to implement FCMP_OEQ.
13905         if (User->getOpcode() == ISD::BR) {
13906           SDValue FalseBB = User->getOperand(1);
13907           SDNode *NewBR =
13908             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13909           assert(NewBR == User);
13910           (void)NewBR;
13911           Dest = FalseBB;
13912
13913           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13914                                     Cond.getOperand(0), Cond.getOperand(1));
13915           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13916           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13917           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13918                               Chain, Dest, CC, Cmp);
13919           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13920           Cond = Cmp;
13921           addTest = false;
13922         }
13923       }
13924     } else if (Cond.getOpcode() == ISD::SETCC &&
13925                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13926       // For FCMP_UNE, we can emit
13927       // two branches instead of an explicit AND instruction with a
13928       // separate test. However, we only do this if this block doesn't
13929       // have a fall-through edge, because this requires an explicit
13930       // jmp when the condition is false.
13931       if (Op.getNode()->hasOneUse()) {
13932         SDNode *User = *Op.getNode()->use_begin();
13933         // Look for an unconditional branch following this conditional branch.
13934         // We need this because we need to reverse the successors in order
13935         // to implement FCMP_UNE.
13936         if (User->getOpcode() == ISD::BR) {
13937           SDValue FalseBB = User->getOperand(1);
13938           SDNode *NewBR =
13939             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13940           assert(NewBR == User);
13941           (void)NewBR;
13942
13943           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13944                                     Cond.getOperand(0), Cond.getOperand(1));
13945           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13946           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13947           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13948                               Chain, Dest, CC, Cmp);
13949           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13950           Cond = Cmp;
13951           addTest = false;
13952           Dest = FalseBB;
13953         }
13954       }
13955     }
13956   }
13957
13958   if (addTest) {
13959     // Look pass the truncate if the high bits are known zero.
13960     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13961         Cond = Cond.getOperand(0);
13962
13963     // We know the result of AND is compared against zero. Try to match
13964     // it to BT.
13965     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13966       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13967       if (NewSetCC.getNode()) {
13968         CC = NewSetCC.getOperand(0);
13969         Cond = NewSetCC.getOperand(1);
13970         addTest = false;
13971       }
13972     }
13973   }
13974
13975   if (addTest) {
13976     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13977     CC = DAG.getConstant(X86Cond, MVT::i8);
13978     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13979   }
13980   Cond = ConvertCmpIfNecessary(Cond, DAG);
13981   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13982                      Chain, Dest, CC, Cond);
13983 }
13984
13985 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13986 // Calls to _alloca are needed to probe the stack when allocating more than 4k
13987 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13988 // that the guard pages used by the OS virtual memory manager are allocated in
13989 // correct sequence.
13990 SDValue
13991 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13992                                            SelectionDAG &DAG) const {
13993   MachineFunction &MF = DAG.getMachineFunction();
13994   bool SplitStack = MF.shouldSplitStack();
13995   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
13996                SplitStack;
13997   SDLoc dl(Op);
13998
13999   if (!Lower) {
14000     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14001     SDNode* Node = Op.getNode();
14002
14003     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14004     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14005         " not tell us which reg is the stack pointer!");
14006     EVT VT = Node->getValueType(0);
14007     SDValue Tmp1 = SDValue(Node, 0);
14008     SDValue Tmp2 = SDValue(Node, 1);
14009     SDValue Tmp3 = Node->getOperand(2);
14010     SDValue Chain = Tmp1.getOperand(0);
14011
14012     // Chain the dynamic stack allocation so that it doesn't modify the stack
14013     // pointer when other instructions are using the stack.
14014     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14015         SDLoc(Node));
14016
14017     SDValue Size = Tmp2.getOperand(1);
14018     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14019     Chain = SP.getValue(1);
14020     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14021     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14022     unsigned StackAlign = TFI.getStackAlignment();
14023     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14024     if (Align > StackAlign)
14025       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14026           DAG.getConstant(-(uint64_t)Align, VT));
14027     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14028
14029     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14030         DAG.getIntPtrConstant(0, true), SDValue(),
14031         SDLoc(Node));
14032
14033     SDValue Ops[2] = { Tmp1, Tmp2 };
14034     return DAG.getMergeValues(Ops, dl);
14035   }
14036
14037   // Get the inputs.
14038   SDValue Chain = Op.getOperand(0);
14039   SDValue Size  = Op.getOperand(1);
14040   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14041   EVT VT = Op.getNode()->getValueType(0);
14042
14043   bool Is64Bit = Subtarget->is64Bit();
14044   EVT SPTy = getPointerTy();
14045
14046   if (SplitStack) {
14047     MachineRegisterInfo &MRI = MF.getRegInfo();
14048
14049     if (Is64Bit) {
14050       // The 64 bit implementation of segmented stacks needs to clobber both r10
14051       // r11. This makes it impossible to use it along with nested parameters.
14052       const Function *F = MF.getFunction();
14053
14054       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14055            I != E; ++I)
14056         if (I->hasNestAttr())
14057           report_fatal_error("Cannot use segmented stacks with functions that "
14058                              "have nested arguments.");
14059     }
14060
14061     const TargetRegisterClass *AddrRegClass =
14062       getRegClassFor(getPointerTy());
14063     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14064     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14065     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14066                                 DAG.getRegister(Vreg, SPTy));
14067     SDValue Ops1[2] = { Value, Chain };
14068     return DAG.getMergeValues(Ops1, dl);
14069   } else {
14070     SDValue Flag;
14071     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14072
14073     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14074     Flag = Chain.getValue(1);
14075     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14076
14077     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14078
14079     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14080     unsigned SPReg = RegInfo->getStackRegister();
14081     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14082     Chain = SP.getValue(1);
14083
14084     if (Align) {
14085       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14086                        DAG.getConstant(-(uint64_t)Align, VT));
14087       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14088     }
14089
14090     SDValue Ops1[2] = { SP, Chain };
14091     return DAG.getMergeValues(Ops1, dl);
14092   }
14093 }
14094
14095 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14096   MachineFunction &MF = DAG.getMachineFunction();
14097   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14098
14099   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14100   SDLoc DL(Op);
14101
14102   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14103     // vastart just stores the address of the VarArgsFrameIndex slot into the
14104     // memory location argument.
14105     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14106                                    getPointerTy());
14107     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14108                         MachinePointerInfo(SV), false, false, 0);
14109   }
14110
14111   // __va_list_tag:
14112   //   gp_offset         (0 - 6 * 8)
14113   //   fp_offset         (48 - 48 + 8 * 16)
14114   //   overflow_arg_area (point to parameters coming in memory).
14115   //   reg_save_area
14116   SmallVector<SDValue, 8> MemOps;
14117   SDValue FIN = Op.getOperand(1);
14118   // Store gp_offset
14119   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14120                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14121                                                MVT::i32),
14122                                FIN, MachinePointerInfo(SV), false, false, 0);
14123   MemOps.push_back(Store);
14124
14125   // Store fp_offset
14126   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14127                     FIN, DAG.getIntPtrConstant(4));
14128   Store = DAG.getStore(Op.getOperand(0), DL,
14129                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14130                                        MVT::i32),
14131                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14132   MemOps.push_back(Store);
14133
14134   // Store ptr to overflow_arg_area
14135   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14136                     FIN, DAG.getIntPtrConstant(4));
14137   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14138                                     getPointerTy());
14139   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14140                        MachinePointerInfo(SV, 8),
14141                        false, false, 0);
14142   MemOps.push_back(Store);
14143
14144   // Store ptr to reg_save_area.
14145   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14146                     FIN, DAG.getIntPtrConstant(8));
14147   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14148                                     getPointerTy());
14149   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14150                        MachinePointerInfo(SV, 16), false, false, 0);
14151   MemOps.push_back(Store);
14152   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14153 }
14154
14155 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14156   assert(Subtarget->is64Bit() &&
14157          "LowerVAARG only handles 64-bit va_arg!");
14158   assert((Subtarget->isTargetLinux() ||
14159           Subtarget->isTargetDarwin()) &&
14160           "Unhandled target in LowerVAARG");
14161   assert(Op.getNode()->getNumOperands() == 4);
14162   SDValue Chain = Op.getOperand(0);
14163   SDValue SrcPtr = Op.getOperand(1);
14164   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14165   unsigned Align = Op.getConstantOperandVal(3);
14166   SDLoc dl(Op);
14167
14168   EVT ArgVT = Op.getNode()->getValueType(0);
14169   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14170   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14171   uint8_t ArgMode;
14172
14173   // Decide which area this value should be read from.
14174   // TODO: Implement the AMD64 ABI in its entirety. This simple
14175   // selection mechanism works only for the basic types.
14176   if (ArgVT == MVT::f80) {
14177     llvm_unreachable("va_arg for f80 not yet implemented");
14178   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14179     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14180   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14181     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14182   } else {
14183     llvm_unreachable("Unhandled argument type in LowerVAARG");
14184   }
14185
14186   if (ArgMode == 2) {
14187     // Sanity Check: Make sure using fp_offset makes sense.
14188     assert(!DAG.getTarget().Options.UseSoftFloat &&
14189            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14190                Attribute::NoImplicitFloat)) &&
14191            Subtarget->hasSSE1());
14192   }
14193
14194   // Insert VAARG_64 node into the DAG
14195   // VAARG_64 returns two values: Variable Argument Address, Chain
14196   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14197                        DAG.getConstant(ArgMode, MVT::i8),
14198                        DAG.getConstant(Align, MVT::i32)};
14199   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14200   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14201                                           VTs, InstOps, MVT::i64,
14202                                           MachinePointerInfo(SV),
14203                                           /*Align=*/0,
14204                                           /*Volatile=*/false,
14205                                           /*ReadMem=*/true,
14206                                           /*WriteMem=*/true);
14207   Chain = VAARG.getValue(1);
14208
14209   // Load the next argument and return it
14210   return DAG.getLoad(ArgVT, dl,
14211                      Chain,
14212                      VAARG,
14213                      MachinePointerInfo(),
14214                      false, false, false, 0);
14215 }
14216
14217 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14218                            SelectionDAG &DAG) {
14219   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14220   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14221   SDValue Chain = Op.getOperand(0);
14222   SDValue DstPtr = Op.getOperand(1);
14223   SDValue SrcPtr = Op.getOperand(2);
14224   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14225   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14226   SDLoc DL(Op);
14227
14228   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14229                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14230                        false,
14231                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14232 }
14233
14234 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14235 // amount is a constant. Takes immediate version of shift as input.
14236 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14237                                           SDValue SrcOp, uint64_t ShiftAmt,
14238                                           SelectionDAG &DAG) {
14239   MVT ElementType = VT.getVectorElementType();
14240
14241   // Fold this packed shift into its first operand if ShiftAmt is 0.
14242   if (ShiftAmt == 0)
14243     return SrcOp;
14244
14245   // Check for ShiftAmt >= element width
14246   if (ShiftAmt >= ElementType.getSizeInBits()) {
14247     if (Opc == X86ISD::VSRAI)
14248       ShiftAmt = ElementType.getSizeInBits() - 1;
14249     else
14250       return DAG.getConstant(0, VT);
14251   }
14252
14253   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14254          && "Unknown target vector shift-by-constant node");
14255
14256   // Fold this packed vector shift into a build vector if SrcOp is a
14257   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14258   if (VT == SrcOp.getSimpleValueType() &&
14259       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14260     SmallVector<SDValue, 8> Elts;
14261     unsigned NumElts = SrcOp->getNumOperands();
14262     ConstantSDNode *ND;
14263
14264     switch(Opc) {
14265     default: llvm_unreachable(nullptr);
14266     case X86ISD::VSHLI:
14267       for (unsigned i=0; i!=NumElts; ++i) {
14268         SDValue CurrentOp = SrcOp->getOperand(i);
14269         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14270           Elts.push_back(CurrentOp);
14271           continue;
14272         }
14273         ND = cast<ConstantSDNode>(CurrentOp);
14274         const APInt &C = ND->getAPIntValue();
14275         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14276       }
14277       break;
14278     case X86ISD::VSRLI:
14279       for (unsigned i=0; i!=NumElts; ++i) {
14280         SDValue CurrentOp = SrcOp->getOperand(i);
14281         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14282           Elts.push_back(CurrentOp);
14283           continue;
14284         }
14285         ND = cast<ConstantSDNode>(CurrentOp);
14286         const APInt &C = ND->getAPIntValue();
14287         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14288       }
14289       break;
14290     case X86ISD::VSRAI:
14291       for (unsigned i=0; i!=NumElts; ++i) {
14292         SDValue CurrentOp = SrcOp->getOperand(i);
14293         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14294           Elts.push_back(CurrentOp);
14295           continue;
14296         }
14297         ND = cast<ConstantSDNode>(CurrentOp);
14298         const APInt &C = ND->getAPIntValue();
14299         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14300       }
14301       break;
14302     }
14303
14304     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14305   }
14306
14307   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14308 }
14309
14310 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14311 // may or may not be a constant. Takes immediate version of shift as input.
14312 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14313                                    SDValue SrcOp, SDValue ShAmt,
14314                                    SelectionDAG &DAG) {
14315   MVT SVT = ShAmt.getSimpleValueType();
14316   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14317
14318   // Catch shift-by-constant.
14319   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14320     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14321                                       CShAmt->getZExtValue(), DAG);
14322
14323   // Change opcode to non-immediate version
14324   switch (Opc) {
14325     default: llvm_unreachable("Unknown target vector shift node");
14326     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14327     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14328     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14329   }
14330
14331   const X86Subtarget &Subtarget =
14332       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14333   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14334       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14335     // Let the shuffle legalizer expand this shift amount node.
14336     SDValue Op0 = ShAmt.getOperand(0);
14337     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14338     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14339   } else {
14340     // Need to build a vector containing shift amount.
14341     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14342     SmallVector<SDValue, 4> ShOps;
14343     ShOps.push_back(ShAmt);
14344     if (SVT == MVT::i32) {
14345       ShOps.push_back(DAG.getConstant(0, SVT));
14346       ShOps.push_back(DAG.getUNDEF(SVT));
14347     }
14348     ShOps.push_back(DAG.getUNDEF(SVT));
14349
14350     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14351     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14352   }
14353
14354   // The return type has to be a 128-bit type with the same element
14355   // type as the input type.
14356   MVT EltVT = VT.getVectorElementType();
14357   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14358
14359   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14360   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14361 }
14362
14363 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14364 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14365 /// necessary casting for \p Mask when lowering masking intrinsics.
14366 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14367                                     SDValue PreservedSrc,
14368                                     const X86Subtarget *Subtarget,
14369                                     SelectionDAG &DAG) {
14370     EVT VT = Op.getValueType();
14371     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14372                                   MVT::i1, VT.getVectorNumElements());
14373     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14374                                      Mask.getValueType().getSizeInBits());
14375     SDLoc dl(Op);
14376
14377     assert(MaskVT.isSimple() && "invalid mask type");
14378
14379     if (isAllOnes(Mask))
14380       return Op;
14381
14382     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14383     // are extracted by EXTRACT_SUBVECTOR.
14384     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14385                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14386                               DAG.getIntPtrConstant(0));
14387
14388     switch (Op.getOpcode()) {
14389       default: break;
14390       case X86ISD::PCMPEQM:
14391       case X86ISD::PCMPGTM:
14392       case X86ISD::CMPM:
14393       case X86ISD::CMPMU:
14394         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14395     }
14396     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14397       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14398     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14399 }
14400
14401 /// \brief Creates an SDNode for a predicated scalar operation.
14402 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14403 /// The mask is comming as MVT::i8 and it should be truncated
14404 /// to MVT::i1 while lowering masking intrinsics.
14405 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14406 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14407 /// a scalar instruction.
14408 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14409                                     SDValue PreservedSrc,
14410                                     const X86Subtarget *Subtarget,
14411                                     SelectionDAG &DAG) {
14412     if (isAllOnes(Mask))
14413       return Op;
14414
14415     EVT VT = Op.getValueType();
14416     SDLoc dl(Op);
14417     // The mask should be of type MVT::i1
14418     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14419
14420     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14421       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14422     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14423 }
14424
14425 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14426                                        SelectionDAG &DAG) {
14427   SDLoc dl(Op);
14428   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14429   EVT VT = Op.getValueType();
14430   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14431   if (IntrData) {
14432     switch(IntrData->Type) {
14433     case INTR_TYPE_1OP:
14434       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14435     case INTR_TYPE_2OP:
14436       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14437         Op.getOperand(2));
14438     case INTR_TYPE_3OP:
14439       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14440         Op.getOperand(2), Op.getOperand(3));
14441     case INTR_TYPE_1OP_MASK_RM: {
14442       SDValue Src = Op.getOperand(1);
14443       SDValue Src0 = Op.getOperand(2);
14444       SDValue Mask = Op.getOperand(3);
14445       SDValue RoundingMode = Op.getOperand(4);
14446       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14447                                               RoundingMode),
14448                                   Mask, Src0, Subtarget, DAG);
14449     }
14450     case INTR_TYPE_SCALAR_MASK_RM: {
14451       SDValue Src1 = Op.getOperand(1);
14452       SDValue Src2 = Op.getOperand(2);
14453       SDValue Src0 = Op.getOperand(3);
14454       SDValue Mask = Op.getOperand(4);
14455       // There are 2 kinds of intrinsics in this group:
14456       // (1) With supress-all-exceptions (sae) - 6 operands
14457       // (2) With rounding mode and sae - 7 operands.
14458       if (Op.getNumOperands() == 6) {
14459         SDValue Sae  = Op.getOperand(5);
14460         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14461                                                 Sae),
14462                                     Mask, Src0, Subtarget, DAG);
14463       }
14464       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14465       SDValue RoundingMode  = Op.getOperand(5);
14466       SDValue Sae  = Op.getOperand(6);
14467       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14468                                               RoundingMode, Sae),
14469                                   Mask, Src0, Subtarget, DAG);
14470     }
14471     case INTR_TYPE_2OP_MASK: {
14472       SDValue Src1 = Op.getOperand(1);
14473       SDValue Src2 = Op.getOperand(2);
14474       SDValue PassThru = Op.getOperand(3);
14475       SDValue Mask = Op.getOperand(4);
14476       // We specify 2 possible opcodes for intrinsics with rounding modes.
14477       // First, we check if the intrinsic may have non-default rounding mode,
14478       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14479       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14480       if (IntrWithRoundingModeOpcode != 0) {
14481         SDValue Rnd = Op.getOperand(5);
14482         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14483         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14484           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14485                                       dl, Op.getValueType(),
14486                                       Src1, Src2, Rnd),
14487                                       Mask, PassThru, Subtarget, DAG);
14488         }
14489       }
14490       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14491                                               Src1,Src2),
14492                                   Mask, PassThru, Subtarget, DAG);
14493     }
14494     case FMA_OP_MASK: {
14495       SDValue Src1 = Op.getOperand(1);
14496       SDValue Src2 = Op.getOperand(2);
14497       SDValue Src3 = Op.getOperand(3);
14498       SDValue Mask = Op.getOperand(4);
14499       // We specify 2 possible opcodes for intrinsics with rounding modes.
14500       // First, we check if the intrinsic may have non-default rounding mode,
14501       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14502       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14503       if (IntrWithRoundingModeOpcode != 0) {
14504         SDValue Rnd = Op.getOperand(5);
14505         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14506             X86::STATIC_ROUNDING::CUR_DIRECTION)
14507           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14508                                                   dl, Op.getValueType(),
14509                                                   Src1, Src2, Src3, Rnd),
14510                                       Mask, Src1, Subtarget, DAG);
14511       }
14512       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14513                                               dl, Op.getValueType(),
14514                                               Src1, Src2, Src3),
14515                                   Mask, Src1, Subtarget, DAG);
14516     }
14517     case CMP_MASK:
14518     case CMP_MASK_CC: {
14519       // Comparison intrinsics with masks.
14520       // Example of transformation:
14521       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14522       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14523       // (i8 (bitcast
14524       //   (v8i1 (insert_subvector undef,
14525       //           (v2i1 (and (PCMPEQM %a, %b),
14526       //                      (extract_subvector
14527       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14528       EVT VT = Op.getOperand(1).getValueType();
14529       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14530                                     VT.getVectorNumElements());
14531       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14532       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14533                                        Mask.getValueType().getSizeInBits());
14534       SDValue Cmp;
14535       if (IntrData->Type == CMP_MASK_CC) {
14536         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14537                     Op.getOperand(2), Op.getOperand(3));
14538       } else {
14539         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14540         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14541                     Op.getOperand(2));
14542       }
14543       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14544                                              DAG.getTargetConstant(0, MaskVT),
14545                                              Subtarget, DAG);
14546       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14547                                 DAG.getUNDEF(BitcastVT), CmpMask,
14548                                 DAG.getIntPtrConstant(0));
14549       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14550     }
14551     case COMI: { // Comparison intrinsics
14552       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14553       SDValue LHS = Op.getOperand(1);
14554       SDValue RHS = Op.getOperand(2);
14555       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14556       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14557       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14558       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14559                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14560       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14561     }
14562     case VSHIFT:
14563       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14564                                  Op.getOperand(1), Op.getOperand(2), DAG);
14565     case VSHIFT_MASK:
14566       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14567                                                       Op.getSimpleValueType(),
14568                                                       Op.getOperand(1),
14569                                                       Op.getOperand(2), DAG),
14570                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14571                                   DAG);
14572     case COMPRESS_EXPAND_IN_REG: {
14573       SDValue Mask = Op.getOperand(3);
14574       SDValue DataToCompress = Op.getOperand(1);
14575       SDValue PassThru = Op.getOperand(2);
14576       if (isAllOnes(Mask)) // return data as is
14577         return Op.getOperand(1);
14578       EVT VT = Op.getValueType();
14579       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14580                                     VT.getVectorNumElements());
14581       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14582                                        Mask.getValueType().getSizeInBits());
14583       SDLoc dl(Op);
14584       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14585                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14586                                   DAG.getIntPtrConstant(0));
14587
14588       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14589                          PassThru);
14590     }
14591     case BLEND: {
14592       SDValue Mask = Op.getOperand(3);
14593       EVT VT = Op.getValueType();
14594       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14595                                     VT.getVectorNumElements());
14596       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14597                                        Mask.getValueType().getSizeInBits());
14598       SDLoc dl(Op);
14599       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14600                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14601                                   DAG.getIntPtrConstant(0));
14602       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14603                          Op.getOperand(2));
14604     }
14605     default:
14606       break;
14607     }
14608   }
14609
14610   switch (IntNo) {
14611   default: return SDValue();    // Don't custom lower most intrinsics.
14612
14613   case Intrinsic::x86_avx512_mask_valign_q_512:
14614   case Intrinsic::x86_avx512_mask_valign_d_512:
14615     // Vector source operands are swapped.
14616     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14617                                             Op.getValueType(), Op.getOperand(2),
14618                                             Op.getOperand(1),
14619                                             Op.getOperand(3)),
14620                                 Op.getOperand(5), Op.getOperand(4),
14621                                 Subtarget, DAG);
14622
14623   // ptest and testp intrinsics. The intrinsic these come from are designed to
14624   // return an integer value, not just an instruction so lower it to the ptest
14625   // or testp pattern and a setcc for the result.
14626   case Intrinsic::x86_sse41_ptestz:
14627   case Intrinsic::x86_sse41_ptestc:
14628   case Intrinsic::x86_sse41_ptestnzc:
14629   case Intrinsic::x86_avx_ptestz_256:
14630   case Intrinsic::x86_avx_ptestc_256:
14631   case Intrinsic::x86_avx_ptestnzc_256:
14632   case Intrinsic::x86_avx_vtestz_ps:
14633   case Intrinsic::x86_avx_vtestc_ps:
14634   case Intrinsic::x86_avx_vtestnzc_ps:
14635   case Intrinsic::x86_avx_vtestz_pd:
14636   case Intrinsic::x86_avx_vtestc_pd:
14637   case Intrinsic::x86_avx_vtestnzc_pd:
14638   case Intrinsic::x86_avx_vtestz_ps_256:
14639   case Intrinsic::x86_avx_vtestc_ps_256:
14640   case Intrinsic::x86_avx_vtestnzc_ps_256:
14641   case Intrinsic::x86_avx_vtestz_pd_256:
14642   case Intrinsic::x86_avx_vtestc_pd_256:
14643   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14644     bool IsTestPacked = false;
14645     unsigned X86CC;
14646     switch (IntNo) {
14647     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14648     case Intrinsic::x86_avx_vtestz_ps:
14649     case Intrinsic::x86_avx_vtestz_pd:
14650     case Intrinsic::x86_avx_vtestz_ps_256:
14651     case Intrinsic::x86_avx_vtestz_pd_256:
14652       IsTestPacked = true; // Fallthrough
14653     case Intrinsic::x86_sse41_ptestz:
14654     case Intrinsic::x86_avx_ptestz_256:
14655       // ZF = 1
14656       X86CC = X86::COND_E;
14657       break;
14658     case Intrinsic::x86_avx_vtestc_ps:
14659     case Intrinsic::x86_avx_vtestc_pd:
14660     case Intrinsic::x86_avx_vtestc_ps_256:
14661     case Intrinsic::x86_avx_vtestc_pd_256:
14662       IsTestPacked = true; // Fallthrough
14663     case Intrinsic::x86_sse41_ptestc:
14664     case Intrinsic::x86_avx_ptestc_256:
14665       // CF = 1
14666       X86CC = X86::COND_B;
14667       break;
14668     case Intrinsic::x86_avx_vtestnzc_ps:
14669     case Intrinsic::x86_avx_vtestnzc_pd:
14670     case Intrinsic::x86_avx_vtestnzc_ps_256:
14671     case Intrinsic::x86_avx_vtestnzc_pd_256:
14672       IsTestPacked = true; // Fallthrough
14673     case Intrinsic::x86_sse41_ptestnzc:
14674     case Intrinsic::x86_avx_ptestnzc_256:
14675       // ZF and CF = 0
14676       X86CC = X86::COND_A;
14677       break;
14678     }
14679
14680     SDValue LHS = Op.getOperand(1);
14681     SDValue RHS = Op.getOperand(2);
14682     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14683     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14684     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14685     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14686     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14687   }
14688   case Intrinsic::x86_avx512_kortestz_w:
14689   case Intrinsic::x86_avx512_kortestc_w: {
14690     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14691     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14692     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14693     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14694     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14695     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14696     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14697   }
14698
14699   case Intrinsic::x86_sse42_pcmpistria128:
14700   case Intrinsic::x86_sse42_pcmpestria128:
14701   case Intrinsic::x86_sse42_pcmpistric128:
14702   case Intrinsic::x86_sse42_pcmpestric128:
14703   case Intrinsic::x86_sse42_pcmpistrio128:
14704   case Intrinsic::x86_sse42_pcmpestrio128:
14705   case Intrinsic::x86_sse42_pcmpistris128:
14706   case Intrinsic::x86_sse42_pcmpestris128:
14707   case Intrinsic::x86_sse42_pcmpistriz128:
14708   case Intrinsic::x86_sse42_pcmpestriz128: {
14709     unsigned Opcode;
14710     unsigned X86CC;
14711     switch (IntNo) {
14712     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14713     case Intrinsic::x86_sse42_pcmpistria128:
14714       Opcode = X86ISD::PCMPISTRI;
14715       X86CC = X86::COND_A;
14716       break;
14717     case Intrinsic::x86_sse42_pcmpestria128:
14718       Opcode = X86ISD::PCMPESTRI;
14719       X86CC = X86::COND_A;
14720       break;
14721     case Intrinsic::x86_sse42_pcmpistric128:
14722       Opcode = X86ISD::PCMPISTRI;
14723       X86CC = X86::COND_B;
14724       break;
14725     case Intrinsic::x86_sse42_pcmpestric128:
14726       Opcode = X86ISD::PCMPESTRI;
14727       X86CC = X86::COND_B;
14728       break;
14729     case Intrinsic::x86_sse42_pcmpistrio128:
14730       Opcode = X86ISD::PCMPISTRI;
14731       X86CC = X86::COND_O;
14732       break;
14733     case Intrinsic::x86_sse42_pcmpestrio128:
14734       Opcode = X86ISD::PCMPESTRI;
14735       X86CC = X86::COND_O;
14736       break;
14737     case Intrinsic::x86_sse42_pcmpistris128:
14738       Opcode = X86ISD::PCMPISTRI;
14739       X86CC = X86::COND_S;
14740       break;
14741     case Intrinsic::x86_sse42_pcmpestris128:
14742       Opcode = X86ISD::PCMPESTRI;
14743       X86CC = X86::COND_S;
14744       break;
14745     case Intrinsic::x86_sse42_pcmpistriz128:
14746       Opcode = X86ISD::PCMPISTRI;
14747       X86CC = X86::COND_E;
14748       break;
14749     case Intrinsic::x86_sse42_pcmpestriz128:
14750       Opcode = X86ISD::PCMPESTRI;
14751       X86CC = X86::COND_E;
14752       break;
14753     }
14754     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14755     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14756     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14757     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14758                                 DAG.getConstant(X86CC, MVT::i8),
14759                                 SDValue(PCMP.getNode(), 1));
14760     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14761   }
14762
14763   case Intrinsic::x86_sse42_pcmpistri128:
14764   case Intrinsic::x86_sse42_pcmpestri128: {
14765     unsigned Opcode;
14766     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14767       Opcode = X86ISD::PCMPISTRI;
14768     else
14769       Opcode = X86ISD::PCMPESTRI;
14770
14771     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14772     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14773     return DAG.getNode(Opcode, dl, VTs, NewOps);
14774   }
14775   }
14776 }
14777
14778 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14779                               SDValue Src, SDValue Mask, SDValue Base,
14780                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14781                               const X86Subtarget * Subtarget) {
14782   SDLoc dl(Op);
14783   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14784   assert(C && "Invalid scale type");
14785   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14786   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14787                              Index.getSimpleValueType().getVectorNumElements());
14788   SDValue MaskInReg;
14789   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14790   if (MaskC)
14791     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14792   else
14793     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14794   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14795   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14796   SDValue Segment = DAG.getRegister(0, MVT::i32);
14797   if (Src.getOpcode() == ISD::UNDEF)
14798     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14799   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14800   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14801   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14802   return DAG.getMergeValues(RetOps, dl);
14803 }
14804
14805 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14806                                SDValue Src, SDValue Mask, SDValue Base,
14807                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14808   SDLoc dl(Op);
14809   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14810   assert(C && "Invalid scale type");
14811   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14812   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14813   SDValue Segment = DAG.getRegister(0, MVT::i32);
14814   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14815                              Index.getSimpleValueType().getVectorNumElements());
14816   SDValue MaskInReg;
14817   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14818   if (MaskC)
14819     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14820   else
14821     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14822   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14823   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14824   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14825   return SDValue(Res, 1);
14826 }
14827
14828 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14829                                SDValue Mask, SDValue Base, SDValue Index,
14830                                SDValue ScaleOp, SDValue Chain) {
14831   SDLoc dl(Op);
14832   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14833   assert(C && "Invalid scale type");
14834   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14835   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14836   SDValue Segment = DAG.getRegister(0, MVT::i32);
14837   EVT MaskVT =
14838     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14839   SDValue MaskInReg;
14840   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14841   if (MaskC)
14842     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14843   else
14844     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14845   //SDVTList VTs = DAG.getVTList(MVT::Other);
14846   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14847   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14848   return SDValue(Res, 0);
14849 }
14850
14851 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14852 // read performance monitor counters (x86_rdpmc).
14853 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14854                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14855                               SmallVectorImpl<SDValue> &Results) {
14856   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14857   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14858   SDValue LO, HI;
14859
14860   // The ECX register is used to select the index of the performance counter
14861   // to read.
14862   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14863                                    N->getOperand(2));
14864   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14865
14866   // Reads the content of a 64-bit performance counter and returns it in the
14867   // registers EDX:EAX.
14868   if (Subtarget->is64Bit()) {
14869     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14870     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14871                             LO.getValue(2));
14872   } else {
14873     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14874     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14875                             LO.getValue(2));
14876   }
14877   Chain = HI.getValue(1);
14878
14879   if (Subtarget->is64Bit()) {
14880     // The EAX register is loaded with the low-order 32 bits. The EDX register
14881     // is loaded with the supported high-order bits of the counter.
14882     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14883                               DAG.getConstant(32, MVT::i8));
14884     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14885     Results.push_back(Chain);
14886     return;
14887   }
14888
14889   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14890   SDValue Ops[] = { LO, HI };
14891   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14892   Results.push_back(Pair);
14893   Results.push_back(Chain);
14894 }
14895
14896 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14897 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14898 // also used to custom lower READCYCLECOUNTER nodes.
14899 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14900                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14901                               SmallVectorImpl<SDValue> &Results) {
14902   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14903   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14904   SDValue LO, HI;
14905
14906   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14907   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14908   // and the EAX register is loaded with the low-order 32 bits.
14909   if (Subtarget->is64Bit()) {
14910     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14911     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14912                             LO.getValue(2));
14913   } else {
14914     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14915     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14916                             LO.getValue(2));
14917   }
14918   SDValue Chain = HI.getValue(1);
14919
14920   if (Opcode == X86ISD::RDTSCP_DAG) {
14921     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14922
14923     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14924     // the ECX register. Add 'ecx' explicitly to the chain.
14925     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14926                                      HI.getValue(2));
14927     // Explicitly store the content of ECX at the location passed in input
14928     // to the 'rdtscp' intrinsic.
14929     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14930                          MachinePointerInfo(), false, false, 0);
14931   }
14932
14933   if (Subtarget->is64Bit()) {
14934     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14935     // the EAX register is loaded with the low-order 32 bits.
14936     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14937                               DAG.getConstant(32, MVT::i8));
14938     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14939     Results.push_back(Chain);
14940     return;
14941   }
14942
14943   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14944   SDValue Ops[] = { LO, HI };
14945   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14946   Results.push_back(Pair);
14947   Results.push_back(Chain);
14948 }
14949
14950 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14951                                      SelectionDAG &DAG) {
14952   SmallVector<SDValue, 2> Results;
14953   SDLoc DL(Op);
14954   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14955                           Results);
14956   return DAG.getMergeValues(Results, DL);
14957 }
14958
14959
14960 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14961                                       SelectionDAG &DAG) {
14962   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14963
14964   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
14965   if (!IntrData)
14966     return SDValue();
14967
14968   SDLoc dl(Op);
14969   switch(IntrData->Type) {
14970   default:
14971     llvm_unreachable("Unknown Intrinsic Type");
14972     break;
14973   case RDSEED:
14974   case RDRAND: {
14975     // Emit the node with the right value type.
14976     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14977     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
14978
14979     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14980     // Otherwise return the value from Rand, which is always 0, casted to i32.
14981     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14982                       DAG.getConstant(1, Op->getValueType(1)),
14983                       DAG.getConstant(X86::COND_B, MVT::i32),
14984                       SDValue(Result.getNode(), 1) };
14985     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14986                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14987                                   Ops);
14988
14989     // Return { result, isValid, chain }.
14990     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14991                        SDValue(Result.getNode(), 2));
14992   }
14993   case GATHER: {
14994   //gather(v1, mask, index, base, scale);
14995     SDValue Chain = Op.getOperand(0);
14996     SDValue Src   = Op.getOperand(2);
14997     SDValue Base  = Op.getOperand(3);
14998     SDValue Index = Op.getOperand(4);
14999     SDValue Mask  = Op.getOperand(5);
15000     SDValue Scale = Op.getOperand(6);
15001     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15002                           Subtarget);
15003   }
15004   case SCATTER: {
15005   //scatter(base, mask, index, v1, scale);
15006     SDValue Chain = Op.getOperand(0);
15007     SDValue Base  = Op.getOperand(2);
15008     SDValue Mask  = Op.getOperand(3);
15009     SDValue Index = Op.getOperand(4);
15010     SDValue Src   = Op.getOperand(5);
15011     SDValue Scale = Op.getOperand(6);
15012     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15013   }
15014   case PREFETCH: {
15015     SDValue Hint = Op.getOperand(6);
15016     unsigned HintVal;
15017     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15018         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15019       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15020     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15021     SDValue Chain = Op.getOperand(0);
15022     SDValue Mask  = Op.getOperand(2);
15023     SDValue Index = Op.getOperand(3);
15024     SDValue Base  = Op.getOperand(4);
15025     SDValue Scale = Op.getOperand(5);
15026     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15027   }
15028   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15029   case RDTSC: {
15030     SmallVector<SDValue, 2> Results;
15031     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15032     return DAG.getMergeValues(Results, dl);
15033   }
15034   // Read Performance Monitoring Counters.
15035   case RDPMC: {
15036     SmallVector<SDValue, 2> Results;
15037     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15038     return DAG.getMergeValues(Results, dl);
15039   }
15040   // XTEST intrinsics.
15041   case XTEST: {
15042     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15043     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15044     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15045                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15046                                 InTrans);
15047     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15048     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15049                        Ret, SDValue(InTrans.getNode(), 1));
15050   }
15051   // ADC/ADCX/SBB
15052   case ADX: {
15053     SmallVector<SDValue, 2> Results;
15054     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15055     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15056     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15057                                 DAG.getConstant(-1, MVT::i8));
15058     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15059                               Op.getOperand(4), GenCF.getValue(1));
15060     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15061                                  Op.getOperand(5), MachinePointerInfo(),
15062                                  false, false, 0);
15063     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15064                                 DAG.getConstant(X86::COND_B, MVT::i8),
15065                                 Res.getValue(1));
15066     Results.push_back(SetCC);
15067     Results.push_back(Store);
15068     return DAG.getMergeValues(Results, dl);
15069   }
15070   case COMPRESS_TO_MEM: {
15071     SDLoc dl(Op);
15072     SDValue Mask = Op.getOperand(4);
15073     SDValue DataToCompress = Op.getOperand(3);
15074     SDValue Addr = Op.getOperand(2);
15075     SDValue Chain = Op.getOperand(0);
15076
15077     if (isAllOnes(Mask)) // return just a store
15078       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15079                           MachinePointerInfo(), false, false, 0);
15080
15081     EVT VT = DataToCompress.getValueType();
15082     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15083                                   VT.getVectorNumElements());
15084     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15085                                      Mask.getValueType().getSizeInBits());
15086     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15087                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15088                                 DAG.getIntPtrConstant(0));
15089
15090     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15091                                       DataToCompress, DAG.getUNDEF(VT));
15092     return DAG.getStore(Chain, dl, Compressed, Addr,
15093                         MachinePointerInfo(), false, false, 0);
15094   }
15095   case EXPAND_FROM_MEM: {
15096     SDLoc dl(Op);
15097     SDValue Mask = Op.getOperand(4);
15098     SDValue PathThru = Op.getOperand(3);
15099     SDValue Addr = Op.getOperand(2);
15100     SDValue Chain = Op.getOperand(0);
15101     EVT VT = Op.getValueType();
15102
15103     if (isAllOnes(Mask)) // return just a load
15104       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15105                          false, 0);
15106     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15107                                   VT.getVectorNumElements());
15108     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15109                                      Mask.getValueType().getSizeInBits());
15110     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15111                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15112                                 DAG.getIntPtrConstant(0));
15113
15114     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15115                                    false, false, false, 0);
15116
15117     SDValue Results[] = {
15118         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15119         Chain};
15120     return DAG.getMergeValues(Results, dl);
15121   }
15122   }
15123 }
15124
15125 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15126                                            SelectionDAG &DAG) const {
15127   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15128   MFI->setReturnAddressIsTaken(true);
15129
15130   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15131     return SDValue();
15132
15133   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15134   SDLoc dl(Op);
15135   EVT PtrVT = getPointerTy();
15136
15137   if (Depth > 0) {
15138     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15139     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15140     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15141     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15142                        DAG.getNode(ISD::ADD, dl, PtrVT,
15143                                    FrameAddr, Offset),
15144                        MachinePointerInfo(), false, false, false, 0);
15145   }
15146
15147   // Just load the return address.
15148   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15149   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15150                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15151 }
15152
15153 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15154   MachineFunction &MF = DAG.getMachineFunction();
15155   MachineFrameInfo *MFI = MF.getFrameInfo();
15156   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15157   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15158   EVT VT = Op.getValueType();
15159
15160   MFI->setFrameAddressIsTaken(true);
15161
15162   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15163     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15164     // is not possible to crawl up the stack without looking at the unwind codes
15165     // simultaneously.
15166     int FrameAddrIndex = FuncInfo->getFAIndex();
15167     if (!FrameAddrIndex) {
15168       // Set up a frame object for the return address.
15169       unsigned SlotSize = RegInfo->getSlotSize();
15170       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15171           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15172       FuncInfo->setFAIndex(FrameAddrIndex);
15173     }
15174     return DAG.getFrameIndex(FrameAddrIndex, VT);
15175   }
15176
15177   unsigned FrameReg =
15178       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15179   SDLoc dl(Op);  // FIXME probably not meaningful
15180   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15181   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15182           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15183          "Invalid Frame Register!");
15184   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15185   while (Depth--)
15186     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15187                             MachinePointerInfo(),
15188                             false, false, false, 0);
15189   return FrameAddr;
15190 }
15191
15192 // FIXME? Maybe this could be a TableGen attribute on some registers and
15193 // this table could be generated automatically from RegInfo.
15194 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15195                                               EVT VT) const {
15196   unsigned Reg = StringSwitch<unsigned>(RegName)
15197                        .Case("esp", X86::ESP)
15198                        .Case("rsp", X86::RSP)
15199                        .Default(0);
15200   if (Reg)
15201     return Reg;
15202   report_fatal_error("Invalid register name global variable");
15203 }
15204
15205 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15206                                                      SelectionDAG &DAG) const {
15207   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15208   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15209 }
15210
15211 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15212   SDValue Chain     = Op.getOperand(0);
15213   SDValue Offset    = Op.getOperand(1);
15214   SDValue Handler   = Op.getOperand(2);
15215   SDLoc dl      (Op);
15216
15217   EVT PtrVT = getPointerTy();
15218   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15219   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15220   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15221           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15222          "Invalid Frame Register!");
15223   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15224   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15225
15226   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15227                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15228   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15229   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15230                        false, false, 0);
15231   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15232
15233   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15234                      DAG.getRegister(StoreAddrReg, PtrVT));
15235 }
15236
15237 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15238                                                SelectionDAG &DAG) const {
15239   SDLoc DL(Op);
15240   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15241                      DAG.getVTList(MVT::i32, MVT::Other),
15242                      Op.getOperand(0), Op.getOperand(1));
15243 }
15244
15245 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15246                                                 SelectionDAG &DAG) const {
15247   SDLoc DL(Op);
15248   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15249                      Op.getOperand(0), Op.getOperand(1));
15250 }
15251
15252 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15253   return Op.getOperand(0);
15254 }
15255
15256 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15257                                                 SelectionDAG &DAG) const {
15258   SDValue Root = Op.getOperand(0);
15259   SDValue Trmp = Op.getOperand(1); // trampoline
15260   SDValue FPtr = Op.getOperand(2); // nested function
15261   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15262   SDLoc dl (Op);
15263
15264   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15265   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15266
15267   if (Subtarget->is64Bit()) {
15268     SDValue OutChains[6];
15269
15270     // Large code-model.
15271     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15272     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15273
15274     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15275     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15276
15277     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15278
15279     // Load the pointer to the nested function into R11.
15280     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15281     SDValue Addr = Trmp;
15282     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15283                                 Addr, MachinePointerInfo(TrmpAddr),
15284                                 false, false, 0);
15285
15286     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15287                        DAG.getConstant(2, MVT::i64));
15288     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15289                                 MachinePointerInfo(TrmpAddr, 2),
15290                                 false, false, 2);
15291
15292     // Load the 'nest' parameter value into R10.
15293     // R10 is specified in X86CallingConv.td
15294     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15295     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15296                        DAG.getConstant(10, MVT::i64));
15297     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15298                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15299                                 false, false, 0);
15300
15301     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15302                        DAG.getConstant(12, MVT::i64));
15303     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15304                                 MachinePointerInfo(TrmpAddr, 12),
15305                                 false, false, 2);
15306
15307     // Jump to the nested function.
15308     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15309     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15310                        DAG.getConstant(20, MVT::i64));
15311     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15312                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15313                                 false, false, 0);
15314
15315     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15316     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15317                        DAG.getConstant(22, MVT::i64));
15318     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15319                                 MachinePointerInfo(TrmpAddr, 22),
15320                                 false, false, 0);
15321
15322     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15323   } else {
15324     const Function *Func =
15325       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15326     CallingConv::ID CC = Func->getCallingConv();
15327     unsigned NestReg;
15328
15329     switch (CC) {
15330     default:
15331       llvm_unreachable("Unsupported calling convention");
15332     case CallingConv::C:
15333     case CallingConv::X86_StdCall: {
15334       // Pass 'nest' parameter in ECX.
15335       // Must be kept in sync with X86CallingConv.td
15336       NestReg = X86::ECX;
15337
15338       // Check that ECX wasn't needed by an 'inreg' parameter.
15339       FunctionType *FTy = Func->getFunctionType();
15340       const AttributeSet &Attrs = Func->getAttributes();
15341
15342       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15343         unsigned InRegCount = 0;
15344         unsigned Idx = 1;
15345
15346         for (FunctionType::param_iterator I = FTy->param_begin(),
15347              E = FTy->param_end(); I != E; ++I, ++Idx)
15348           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15349             // FIXME: should only count parameters that are lowered to integers.
15350             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15351
15352         if (InRegCount > 2) {
15353           report_fatal_error("Nest register in use - reduce number of inreg"
15354                              " parameters!");
15355         }
15356       }
15357       break;
15358     }
15359     case CallingConv::X86_FastCall:
15360     case CallingConv::X86_ThisCall:
15361     case CallingConv::Fast:
15362       // Pass 'nest' parameter in EAX.
15363       // Must be kept in sync with X86CallingConv.td
15364       NestReg = X86::EAX;
15365       break;
15366     }
15367
15368     SDValue OutChains[4];
15369     SDValue Addr, Disp;
15370
15371     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15372                        DAG.getConstant(10, MVT::i32));
15373     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15374
15375     // This is storing the opcode for MOV32ri.
15376     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15377     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15378     OutChains[0] = DAG.getStore(Root, dl,
15379                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15380                                 Trmp, MachinePointerInfo(TrmpAddr),
15381                                 false, false, 0);
15382
15383     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15384                        DAG.getConstant(1, MVT::i32));
15385     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15386                                 MachinePointerInfo(TrmpAddr, 1),
15387                                 false, false, 1);
15388
15389     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15390     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15391                        DAG.getConstant(5, MVT::i32));
15392     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15393                                 MachinePointerInfo(TrmpAddr, 5),
15394                                 false, false, 1);
15395
15396     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15397                        DAG.getConstant(6, MVT::i32));
15398     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15399                                 MachinePointerInfo(TrmpAddr, 6),
15400                                 false, false, 1);
15401
15402     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15403   }
15404 }
15405
15406 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15407                                             SelectionDAG &DAG) const {
15408   /*
15409    The rounding mode is in bits 11:10 of FPSR, and has the following
15410    settings:
15411      00 Round to nearest
15412      01 Round to -inf
15413      10 Round to +inf
15414      11 Round to 0
15415
15416   FLT_ROUNDS, on the other hand, expects the following:
15417     -1 Undefined
15418      0 Round to 0
15419      1 Round to nearest
15420      2 Round to +inf
15421      3 Round to -inf
15422
15423   To perform the conversion, we do:
15424     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15425   */
15426
15427   MachineFunction &MF = DAG.getMachineFunction();
15428   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15429   unsigned StackAlignment = TFI.getStackAlignment();
15430   MVT VT = Op.getSimpleValueType();
15431   SDLoc DL(Op);
15432
15433   // Save FP Control Word to stack slot
15434   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15435   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15436
15437   MachineMemOperand *MMO =
15438    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15439                            MachineMemOperand::MOStore, 2, 2);
15440
15441   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15442   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15443                                           DAG.getVTList(MVT::Other),
15444                                           Ops, MVT::i16, MMO);
15445
15446   // Load FP Control Word from stack slot
15447   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15448                             MachinePointerInfo(), false, false, false, 0);
15449
15450   // Transform as necessary
15451   SDValue CWD1 =
15452     DAG.getNode(ISD::SRL, DL, MVT::i16,
15453                 DAG.getNode(ISD::AND, DL, MVT::i16,
15454                             CWD, DAG.getConstant(0x800, MVT::i16)),
15455                 DAG.getConstant(11, MVT::i8));
15456   SDValue CWD2 =
15457     DAG.getNode(ISD::SRL, DL, MVT::i16,
15458                 DAG.getNode(ISD::AND, DL, MVT::i16,
15459                             CWD, DAG.getConstant(0x400, MVT::i16)),
15460                 DAG.getConstant(9, MVT::i8));
15461
15462   SDValue RetVal =
15463     DAG.getNode(ISD::AND, DL, MVT::i16,
15464                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15465                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15466                             DAG.getConstant(1, MVT::i16)),
15467                 DAG.getConstant(3, MVT::i16));
15468
15469   return DAG.getNode((VT.getSizeInBits() < 16 ?
15470                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15471 }
15472
15473 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15474   MVT VT = Op.getSimpleValueType();
15475   EVT OpVT = VT;
15476   unsigned NumBits = VT.getSizeInBits();
15477   SDLoc dl(Op);
15478
15479   Op = Op.getOperand(0);
15480   if (VT == MVT::i8) {
15481     // Zero extend to i32 since there is not an i8 bsr.
15482     OpVT = MVT::i32;
15483     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15484   }
15485
15486   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15487   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15488   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15489
15490   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15491   SDValue Ops[] = {
15492     Op,
15493     DAG.getConstant(NumBits+NumBits-1, OpVT),
15494     DAG.getConstant(X86::COND_E, MVT::i8),
15495     Op.getValue(1)
15496   };
15497   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15498
15499   // Finally xor with NumBits-1.
15500   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15501
15502   if (VT == MVT::i8)
15503     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15504   return Op;
15505 }
15506
15507 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15508   MVT VT = Op.getSimpleValueType();
15509   EVT OpVT = VT;
15510   unsigned NumBits = VT.getSizeInBits();
15511   SDLoc dl(Op);
15512
15513   Op = Op.getOperand(0);
15514   if (VT == MVT::i8) {
15515     // Zero extend to i32 since there is not an i8 bsr.
15516     OpVT = MVT::i32;
15517     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15518   }
15519
15520   // Issue a bsr (scan bits in reverse).
15521   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15522   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15523
15524   // And xor with NumBits-1.
15525   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15526
15527   if (VT == MVT::i8)
15528     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15529   return Op;
15530 }
15531
15532 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15533   MVT VT = Op.getSimpleValueType();
15534   unsigned NumBits = VT.getSizeInBits();
15535   SDLoc dl(Op);
15536   Op = Op.getOperand(0);
15537
15538   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15539   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15540   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15541
15542   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15543   SDValue Ops[] = {
15544     Op,
15545     DAG.getConstant(NumBits, VT),
15546     DAG.getConstant(X86::COND_E, MVT::i8),
15547     Op.getValue(1)
15548   };
15549   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15550 }
15551
15552 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15553 // ones, and then concatenate the result back.
15554 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15555   MVT VT = Op.getSimpleValueType();
15556
15557   assert(VT.is256BitVector() && VT.isInteger() &&
15558          "Unsupported value type for operation");
15559
15560   unsigned NumElems = VT.getVectorNumElements();
15561   SDLoc dl(Op);
15562
15563   // Extract the LHS vectors
15564   SDValue LHS = Op.getOperand(0);
15565   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15566   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15567
15568   // Extract the RHS vectors
15569   SDValue RHS = Op.getOperand(1);
15570   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15571   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15572
15573   MVT EltVT = VT.getVectorElementType();
15574   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15575
15576   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15577                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15578                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15579 }
15580
15581 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15582   assert(Op.getSimpleValueType().is256BitVector() &&
15583          Op.getSimpleValueType().isInteger() &&
15584          "Only handle AVX 256-bit vector integer operation");
15585   return Lower256IntArith(Op, DAG);
15586 }
15587
15588 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15589   assert(Op.getSimpleValueType().is256BitVector() &&
15590          Op.getSimpleValueType().isInteger() &&
15591          "Only handle AVX 256-bit vector integer operation");
15592   return Lower256IntArith(Op, DAG);
15593 }
15594
15595 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15596                         SelectionDAG &DAG) {
15597   SDLoc dl(Op);
15598   MVT VT = Op.getSimpleValueType();
15599
15600   // Decompose 256-bit ops into smaller 128-bit ops.
15601   if (VT.is256BitVector() && !Subtarget->hasInt256())
15602     return Lower256IntArith(Op, DAG);
15603
15604   SDValue A = Op.getOperand(0);
15605   SDValue B = Op.getOperand(1);
15606
15607   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15608   if (VT == MVT::v4i32) {
15609     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15610            "Should not custom lower when pmuldq is available!");
15611
15612     // Extract the odd parts.
15613     static const int UnpackMask[] = { 1, -1, 3, -1 };
15614     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15615     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15616
15617     // Multiply the even parts.
15618     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15619     // Now multiply odd parts.
15620     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15621
15622     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15623     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15624
15625     // Merge the two vectors back together with a shuffle. This expands into 2
15626     // shuffles.
15627     static const int ShufMask[] = { 0, 4, 2, 6 };
15628     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15629   }
15630
15631   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15632          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15633
15634   //  Ahi = psrlqi(a, 32);
15635   //  Bhi = psrlqi(b, 32);
15636   //
15637   //  AloBlo = pmuludq(a, b);
15638   //  AloBhi = pmuludq(a, Bhi);
15639   //  AhiBlo = pmuludq(Ahi, b);
15640
15641   //  AloBhi = psllqi(AloBhi, 32);
15642   //  AhiBlo = psllqi(AhiBlo, 32);
15643   //  return AloBlo + AloBhi + AhiBlo;
15644
15645   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15646   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15647
15648   // Bit cast to 32-bit vectors for MULUDQ
15649   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15650                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15651   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15652   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15653   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15654   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15655
15656   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15657   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15658   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15659
15660   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15661   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15662
15663   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15664   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15665 }
15666
15667 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15668   assert(Subtarget->isTargetWin64() && "Unexpected target");
15669   EVT VT = Op.getValueType();
15670   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15671          "Unexpected return type for lowering");
15672
15673   RTLIB::Libcall LC;
15674   bool isSigned;
15675   switch (Op->getOpcode()) {
15676   default: llvm_unreachable("Unexpected request for libcall!");
15677   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15678   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15679   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15680   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15681   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15682   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15683   }
15684
15685   SDLoc dl(Op);
15686   SDValue InChain = DAG.getEntryNode();
15687
15688   TargetLowering::ArgListTy Args;
15689   TargetLowering::ArgListEntry Entry;
15690   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15691     EVT ArgVT = Op->getOperand(i).getValueType();
15692     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15693            "Unexpected argument type for lowering");
15694     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15695     Entry.Node = StackPtr;
15696     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15697                            false, false, 16);
15698     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15699     Entry.Ty = PointerType::get(ArgTy,0);
15700     Entry.isSExt = false;
15701     Entry.isZExt = false;
15702     Args.push_back(Entry);
15703   }
15704
15705   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15706                                          getPointerTy());
15707
15708   TargetLowering::CallLoweringInfo CLI(DAG);
15709   CLI.setDebugLoc(dl).setChain(InChain)
15710     .setCallee(getLibcallCallingConv(LC),
15711                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15712                Callee, std::move(Args), 0)
15713     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15714
15715   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15716   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15717 }
15718
15719 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15720                              SelectionDAG &DAG) {
15721   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15722   EVT VT = Op0.getValueType();
15723   SDLoc dl(Op);
15724
15725   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15726          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15727
15728   // PMULxD operations multiply each even value (starting at 0) of LHS with
15729   // the related value of RHS and produce a widen result.
15730   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15731   // => <2 x i64> <ae|cg>
15732   //
15733   // In other word, to have all the results, we need to perform two PMULxD:
15734   // 1. one with the even values.
15735   // 2. one with the odd values.
15736   // To achieve #2, with need to place the odd values at an even position.
15737   //
15738   // Place the odd value at an even position (basically, shift all values 1
15739   // step to the left):
15740   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15741   // <a|b|c|d> => <b|undef|d|undef>
15742   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15743   // <e|f|g|h> => <f|undef|h|undef>
15744   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15745
15746   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15747   // ints.
15748   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15749   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15750   unsigned Opcode =
15751       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15752   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15753   // => <2 x i64> <ae|cg>
15754   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15755                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15756   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15757   // => <2 x i64> <bf|dh>
15758   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15759                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15760
15761   // Shuffle it back into the right order.
15762   SDValue Highs, Lows;
15763   if (VT == MVT::v8i32) {
15764     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15765     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15766     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15767     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15768   } else {
15769     const int HighMask[] = {1, 5, 3, 7};
15770     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15771     const int LowMask[] = {0, 4, 2, 6};
15772     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15773   }
15774
15775   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15776   // unsigned multiply.
15777   if (IsSigned && !Subtarget->hasSSE41()) {
15778     SDValue ShAmt =
15779         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15780     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15781                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15782     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15783                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15784
15785     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15786     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15787   }
15788
15789   // The first result of MUL_LOHI is actually the low value, followed by the
15790   // high value.
15791   SDValue Ops[] = {Lows, Highs};
15792   return DAG.getMergeValues(Ops, dl);
15793 }
15794
15795 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15796                                          const X86Subtarget *Subtarget) {
15797   MVT VT = Op.getSimpleValueType();
15798   SDLoc dl(Op);
15799   SDValue R = Op.getOperand(0);
15800   SDValue Amt = Op.getOperand(1);
15801
15802   // Optimize shl/srl/sra with constant shift amount.
15803   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15804     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15805       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15806
15807       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15808           (Subtarget->hasInt256() &&
15809            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15810           (Subtarget->hasAVX512() &&
15811            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15812         if (Op.getOpcode() == ISD::SHL)
15813           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15814                                             DAG);
15815         if (Op.getOpcode() == ISD::SRL)
15816           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15817                                             DAG);
15818         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15819           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15820                                             DAG);
15821       }
15822
15823       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
15824         unsigned NumElts = VT.getVectorNumElements();
15825         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
15826
15827         if (Op.getOpcode() == ISD::SHL) {
15828           // Make a large shift.
15829           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
15830                                                    R, ShiftAmt, DAG);
15831           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15832           // Zero out the rightmost bits.
15833           SmallVector<SDValue, 32> V(
15834               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
15835           return DAG.getNode(ISD::AND, dl, VT, SHL,
15836                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15837         }
15838         if (Op.getOpcode() == ISD::SRL) {
15839           // Make a large shift.
15840           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
15841                                                    R, ShiftAmt, DAG);
15842           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15843           // Zero out the leftmost bits.
15844           SmallVector<SDValue, 32> V(
15845               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
15846           return DAG.getNode(ISD::AND, dl, VT, SRL,
15847                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15848         }
15849         if (Op.getOpcode() == ISD::SRA) {
15850           if (ShiftAmt == 7) {
15851             // R s>> 7  ===  R s< 0
15852             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15853             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15854           }
15855
15856           // R s>> a === ((R u>> a) ^ m) - m
15857           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15858           SmallVector<SDValue, 32> V(NumElts,
15859                                      DAG.getConstant(128 >> ShiftAmt, MVT::i8));
15860           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15861           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15862           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15863           return Res;
15864         }
15865         llvm_unreachable("Unknown shift opcode.");
15866       }
15867     }
15868   }
15869
15870   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15871   if (!Subtarget->is64Bit() &&
15872       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15873       Amt.getOpcode() == ISD::BITCAST &&
15874       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15875     Amt = Amt.getOperand(0);
15876     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15877                      VT.getVectorNumElements();
15878     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15879     uint64_t ShiftAmt = 0;
15880     for (unsigned i = 0; i != Ratio; ++i) {
15881       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15882       if (!C)
15883         return SDValue();
15884       // 6 == Log2(64)
15885       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15886     }
15887     // Check remaining shift amounts.
15888     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15889       uint64_t ShAmt = 0;
15890       for (unsigned j = 0; j != Ratio; ++j) {
15891         ConstantSDNode *C =
15892           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15893         if (!C)
15894           return SDValue();
15895         // 6 == Log2(64)
15896         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15897       }
15898       if (ShAmt != ShiftAmt)
15899         return SDValue();
15900     }
15901     switch (Op.getOpcode()) {
15902     default:
15903       llvm_unreachable("Unknown shift opcode!");
15904     case ISD::SHL:
15905       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15906                                         DAG);
15907     case ISD::SRL:
15908       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15909                                         DAG);
15910     case ISD::SRA:
15911       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15912                                         DAG);
15913     }
15914   }
15915
15916   return SDValue();
15917 }
15918
15919 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15920                                         const X86Subtarget* Subtarget) {
15921   MVT VT = Op.getSimpleValueType();
15922   SDLoc dl(Op);
15923   SDValue R = Op.getOperand(0);
15924   SDValue Amt = Op.getOperand(1);
15925
15926   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15927       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15928       (Subtarget->hasInt256() &&
15929        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15930         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15931        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15932     SDValue BaseShAmt;
15933     EVT EltVT = VT.getVectorElementType();
15934
15935     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
15936       // Check if this build_vector node is doing a splat.
15937       // If so, then set BaseShAmt equal to the splat value.
15938       BaseShAmt = BV->getSplatValue();
15939       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
15940         BaseShAmt = SDValue();
15941     } else {
15942       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15943         Amt = Amt.getOperand(0);
15944
15945       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
15946       if (SVN && SVN->isSplat()) {
15947         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
15948         SDValue InVec = Amt.getOperand(0);
15949         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15950           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
15951                  "Unexpected shuffle index found!");
15952           BaseShAmt = InVec.getOperand(SplatIdx);
15953         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15954            if (ConstantSDNode *C =
15955                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15956              if (C->getZExtValue() == SplatIdx)
15957                BaseShAmt = InVec.getOperand(1);
15958            }
15959         }
15960
15961         if (!BaseShAmt)
15962           // Avoid introducing an extract element from a shuffle.
15963           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
15964                                     DAG.getIntPtrConstant(SplatIdx));
15965       }
15966     }
15967
15968     if (BaseShAmt.getNode()) {
15969       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
15970       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
15971         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
15972       else if (EltVT.bitsLT(MVT::i32))
15973         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15974
15975       switch (Op.getOpcode()) {
15976       default:
15977         llvm_unreachable("Unknown shift opcode!");
15978       case ISD::SHL:
15979         switch (VT.SimpleTy) {
15980         default: return SDValue();
15981         case MVT::v2i64:
15982         case MVT::v4i32:
15983         case MVT::v8i16:
15984         case MVT::v4i64:
15985         case MVT::v8i32:
15986         case MVT::v16i16:
15987         case MVT::v16i32:
15988         case MVT::v8i64:
15989           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15990         }
15991       case ISD::SRA:
15992         switch (VT.SimpleTy) {
15993         default: return SDValue();
15994         case MVT::v4i32:
15995         case MVT::v8i16:
15996         case MVT::v8i32:
15997         case MVT::v16i16:
15998         case MVT::v16i32:
15999         case MVT::v8i64:
16000           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16001         }
16002       case ISD::SRL:
16003         switch (VT.SimpleTy) {
16004         default: return SDValue();
16005         case MVT::v2i64:
16006         case MVT::v4i32:
16007         case MVT::v8i16:
16008         case MVT::v4i64:
16009         case MVT::v8i32:
16010         case MVT::v16i16:
16011         case MVT::v16i32:
16012         case MVT::v8i64:
16013           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16014         }
16015       }
16016     }
16017   }
16018
16019   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16020   if (!Subtarget->is64Bit() &&
16021       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16022       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16023       Amt.getOpcode() == ISD::BITCAST &&
16024       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16025     Amt = Amt.getOperand(0);
16026     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16027                      VT.getVectorNumElements();
16028     std::vector<SDValue> Vals(Ratio);
16029     for (unsigned i = 0; i != Ratio; ++i)
16030       Vals[i] = Amt.getOperand(i);
16031     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16032       for (unsigned j = 0; j != Ratio; ++j)
16033         if (Vals[j] != Amt.getOperand(i + j))
16034           return SDValue();
16035     }
16036     switch (Op.getOpcode()) {
16037     default:
16038       llvm_unreachable("Unknown shift opcode!");
16039     case ISD::SHL:
16040       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16041     case ISD::SRL:
16042       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16043     case ISD::SRA:
16044       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16045     }
16046   }
16047
16048   return SDValue();
16049 }
16050
16051 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16052                           SelectionDAG &DAG) {
16053   MVT VT = Op.getSimpleValueType();
16054   SDLoc dl(Op);
16055   SDValue R = Op.getOperand(0);
16056   SDValue Amt = Op.getOperand(1);
16057   SDValue V;
16058
16059   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16060   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16061
16062   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16063   if (V.getNode())
16064     return V;
16065
16066   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16067   if (V.getNode())
16068       return V;
16069
16070   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16071     return Op;
16072   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16073   if (Subtarget->hasInt256()) {
16074     if (Op.getOpcode() == ISD::SRL &&
16075         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16076          VT == MVT::v4i64 || VT == MVT::v8i32))
16077       return Op;
16078     if (Op.getOpcode() == ISD::SHL &&
16079         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16080          VT == MVT::v4i64 || VT == MVT::v8i32))
16081       return Op;
16082     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16083       return Op;
16084   }
16085
16086   // If possible, lower this packed shift into a vector multiply instead of
16087   // expanding it into a sequence of scalar shifts.
16088   // Do this only if the vector shift count is a constant build_vector.
16089   if (Op.getOpcode() == ISD::SHL &&
16090       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16091        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16092       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16093     SmallVector<SDValue, 8> Elts;
16094     EVT SVT = VT.getScalarType();
16095     unsigned SVTBits = SVT.getSizeInBits();
16096     const APInt &One = APInt(SVTBits, 1);
16097     unsigned NumElems = VT.getVectorNumElements();
16098
16099     for (unsigned i=0; i !=NumElems; ++i) {
16100       SDValue Op = Amt->getOperand(i);
16101       if (Op->getOpcode() == ISD::UNDEF) {
16102         Elts.push_back(Op);
16103         continue;
16104       }
16105
16106       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16107       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16108       uint64_t ShAmt = C.getZExtValue();
16109       if (ShAmt >= SVTBits) {
16110         Elts.push_back(DAG.getUNDEF(SVT));
16111         continue;
16112       }
16113       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16114     }
16115     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16116     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16117   }
16118
16119   // Lower SHL with variable shift amount.
16120   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16121     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16122
16123     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16124     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16125     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16126     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16127   }
16128
16129   // If possible, lower this shift as a sequence of two shifts by
16130   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16131   // Example:
16132   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16133   //
16134   // Could be rewritten as:
16135   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16136   //
16137   // The advantage is that the two shifts from the example would be
16138   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16139   // the vector shift into four scalar shifts plus four pairs of vector
16140   // insert/extract.
16141   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16142       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16143     unsigned TargetOpcode = X86ISD::MOVSS;
16144     bool CanBeSimplified;
16145     // The splat value for the first packed shift (the 'X' from the example).
16146     SDValue Amt1 = Amt->getOperand(0);
16147     // The splat value for the second packed shift (the 'Y' from the example).
16148     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16149                                         Amt->getOperand(2);
16150
16151     // See if it is possible to replace this node with a sequence of
16152     // two shifts followed by a MOVSS/MOVSD
16153     if (VT == MVT::v4i32) {
16154       // Check if it is legal to use a MOVSS.
16155       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16156                         Amt2 == Amt->getOperand(3);
16157       if (!CanBeSimplified) {
16158         // Otherwise, check if we can still simplify this node using a MOVSD.
16159         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16160                           Amt->getOperand(2) == Amt->getOperand(3);
16161         TargetOpcode = X86ISD::MOVSD;
16162         Amt2 = Amt->getOperand(2);
16163       }
16164     } else {
16165       // Do similar checks for the case where the machine value type
16166       // is MVT::v8i16.
16167       CanBeSimplified = Amt1 == Amt->getOperand(1);
16168       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16169         CanBeSimplified = Amt2 == Amt->getOperand(i);
16170
16171       if (!CanBeSimplified) {
16172         TargetOpcode = X86ISD::MOVSD;
16173         CanBeSimplified = true;
16174         Amt2 = Amt->getOperand(4);
16175         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16176           CanBeSimplified = Amt1 == Amt->getOperand(i);
16177         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16178           CanBeSimplified = Amt2 == Amt->getOperand(j);
16179       }
16180     }
16181
16182     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16183         isa<ConstantSDNode>(Amt2)) {
16184       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16185       EVT CastVT = MVT::v4i32;
16186       SDValue Splat1 =
16187         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16188       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16189       SDValue Splat2 =
16190         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16191       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16192       if (TargetOpcode == X86ISD::MOVSD)
16193         CastVT = MVT::v2i64;
16194       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16195       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16196       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16197                                             BitCast1, DAG);
16198       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16199     }
16200   }
16201
16202   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16203     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16204
16205     // a = a << 5;
16206     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16207     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16208
16209     // Turn 'a' into a mask suitable for VSELECT
16210     SDValue VSelM = DAG.getConstant(0x80, VT);
16211     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16212     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16213
16214     SDValue CM1 = DAG.getConstant(0x0f, VT);
16215     SDValue CM2 = DAG.getConstant(0x3f, VT);
16216
16217     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16218     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16219     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16220     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16221     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16222
16223     // a += a
16224     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16225     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16226     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16227
16228     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16229     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16230     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16231     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16232     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16233
16234     // a += a
16235     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16236     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16237     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16238
16239     // return VSELECT(r, r+r, a);
16240     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16241                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16242     return R;
16243   }
16244
16245   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16246   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16247   // solution better.
16248   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16249     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16250     unsigned ExtOpc =
16251         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16252     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16253     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16254     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16255                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16256   }
16257
16258   // Decompose 256-bit shifts into smaller 128-bit shifts.
16259   if (VT.is256BitVector()) {
16260     unsigned NumElems = VT.getVectorNumElements();
16261     MVT EltVT = VT.getVectorElementType();
16262     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16263
16264     // Extract the two vectors
16265     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16266     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16267
16268     // Recreate the shift amount vectors
16269     SDValue Amt1, Amt2;
16270     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16271       // Constant shift amount
16272       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16273       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16274       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16275
16276       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16277       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16278     } else {
16279       // Variable shift amount
16280       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16281       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16282     }
16283
16284     // Issue new vector shifts for the smaller types
16285     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16286     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16287
16288     // Concatenate the result back
16289     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16290   }
16291
16292   return SDValue();
16293 }
16294
16295 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16296   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16297   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16298   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16299   // has only one use.
16300   SDNode *N = Op.getNode();
16301   SDValue LHS = N->getOperand(0);
16302   SDValue RHS = N->getOperand(1);
16303   unsigned BaseOp = 0;
16304   unsigned Cond = 0;
16305   SDLoc DL(Op);
16306   switch (Op.getOpcode()) {
16307   default: llvm_unreachable("Unknown ovf instruction!");
16308   case ISD::SADDO:
16309     // A subtract of one will be selected as a INC. Note that INC doesn't
16310     // set CF, so we can't do this for UADDO.
16311     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16312       if (C->isOne()) {
16313         BaseOp = X86ISD::INC;
16314         Cond = X86::COND_O;
16315         break;
16316       }
16317     BaseOp = X86ISD::ADD;
16318     Cond = X86::COND_O;
16319     break;
16320   case ISD::UADDO:
16321     BaseOp = X86ISD::ADD;
16322     Cond = X86::COND_B;
16323     break;
16324   case ISD::SSUBO:
16325     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16326     // set CF, so we can't do this for USUBO.
16327     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16328       if (C->isOne()) {
16329         BaseOp = X86ISD::DEC;
16330         Cond = X86::COND_O;
16331         break;
16332       }
16333     BaseOp = X86ISD::SUB;
16334     Cond = X86::COND_O;
16335     break;
16336   case ISD::USUBO:
16337     BaseOp = X86ISD::SUB;
16338     Cond = X86::COND_B;
16339     break;
16340   case ISD::SMULO:
16341     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16342     Cond = X86::COND_O;
16343     break;
16344   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16345     if (N->getValueType(0) == MVT::i8) {
16346       BaseOp = X86ISD::UMUL8;
16347       Cond = X86::COND_O;
16348       break;
16349     }
16350     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16351                                  MVT::i32);
16352     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16353
16354     SDValue SetCC =
16355       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16356                   DAG.getConstant(X86::COND_O, MVT::i32),
16357                   SDValue(Sum.getNode(), 2));
16358
16359     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16360   }
16361   }
16362
16363   // Also sets EFLAGS.
16364   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16365   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16366
16367   SDValue SetCC =
16368     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16369                 DAG.getConstant(Cond, MVT::i32),
16370                 SDValue(Sum.getNode(), 1));
16371
16372   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16373 }
16374
16375 /// Returns true if the operand type is exactly twice the native width, and
16376 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16377 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16378 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16379 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16380   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16381
16382   if (OpWidth == 64)
16383     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16384   else if (OpWidth == 128)
16385     return Subtarget->hasCmpxchg16b();
16386   else
16387     return false;
16388 }
16389
16390 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16391   return needsCmpXchgNb(SI->getValueOperand()->getType());
16392 }
16393
16394 // Note: this turns large loads into lock cmpxchg8b/16b.
16395 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16396 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16397   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16398   return needsCmpXchgNb(PTy->getElementType());
16399 }
16400
16401 TargetLoweringBase::AtomicRMWExpansionKind
16402 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16403   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16404   const Type *MemType = AI->getType();
16405
16406   // If the operand is too big, we must see if cmpxchg8/16b is available
16407   // and default to library calls otherwise.
16408   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16409     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16410                                    : AtomicRMWExpansionKind::None;
16411   }
16412
16413   AtomicRMWInst::BinOp Op = AI->getOperation();
16414   switch (Op) {
16415   default:
16416     llvm_unreachable("Unknown atomic operation");
16417   case AtomicRMWInst::Xchg:
16418   case AtomicRMWInst::Add:
16419   case AtomicRMWInst::Sub:
16420     // It's better to use xadd, xsub or xchg for these in all cases.
16421     return AtomicRMWExpansionKind::None;
16422   case AtomicRMWInst::Or:
16423   case AtomicRMWInst::And:
16424   case AtomicRMWInst::Xor:
16425     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16426     // prefix to a normal instruction for these operations.
16427     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16428                             : AtomicRMWExpansionKind::None;
16429   case AtomicRMWInst::Nand:
16430   case AtomicRMWInst::Max:
16431   case AtomicRMWInst::Min:
16432   case AtomicRMWInst::UMax:
16433   case AtomicRMWInst::UMin:
16434     // These always require a non-trivial set of data operations on x86. We must
16435     // use a cmpxchg loop.
16436     return AtomicRMWExpansionKind::CmpXChg;
16437   }
16438 }
16439
16440 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16441   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16442   // no-sse2). There isn't any reason to disable it if the target processor
16443   // supports it.
16444   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16445 }
16446
16447 LoadInst *
16448 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16449   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16450   const Type *MemType = AI->getType();
16451   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16452   // there is no benefit in turning such RMWs into loads, and it is actually
16453   // harmful as it introduces a mfence.
16454   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16455     return nullptr;
16456
16457   auto Builder = IRBuilder<>(AI);
16458   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16459   auto SynchScope = AI->getSynchScope();
16460   // We must restrict the ordering to avoid generating loads with Release or
16461   // ReleaseAcquire orderings.
16462   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16463   auto Ptr = AI->getPointerOperand();
16464
16465   // Before the load we need a fence. Here is an example lifted from
16466   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16467   // is required:
16468   // Thread 0:
16469   //   x.store(1, relaxed);
16470   //   r1 = y.fetch_add(0, release);
16471   // Thread 1:
16472   //   y.fetch_add(42, acquire);
16473   //   r2 = x.load(relaxed);
16474   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16475   // lowered to just a load without a fence. A mfence flushes the store buffer,
16476   // making the optimization clearly correct.
16477   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16478   // otherwise, we might be able to be more agressive on relaxed idempotent
16479   // rmw. In practice, they do not look useful, so we don't try to be
16480   // especially clever.
16481   if (SynchScope == SingleThread) {
16482     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16483     // the IR level, so we must wrap it in an intrinsic.
16484     return nullptr;
16485   } else if (hasMFENCE(*Subtarget)) {
16486     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16487             Intrinsic::x86_sse2_mfence);
16488     Builder.CreateCall(MFence);
16489   } else {
16490     // FIXME: it might make sense to use a locked operation here but on a
16491     // different cache-line to prevent cache-line bouncing. In practice it
16492     // is probably a small win, and x86 processors without mfence are rare
16493     // enough that we do not bother.
16494     return nullptr;
16495   }
16496
16497   // Finally we can emit the atomic load.
16498   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16499           AI->getType()->getPrimitiveSizeInBits());
16500   Loaded->setAtomic(Order, SynchScope);
16501   AI->replaceAllUsesWith(Loaded);
16502   AI->eraseFromParent();
16503   return Loaded;
16504 }
16505
16506 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16507                                  SelectionDAG &DAG) {
16508   SDLoc dl(Op);
16509   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16510     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16511   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16512     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16513
16514   // The only fence that needs an instruction is a sequentially-consistent
16515   // cross-thread fence.
16516   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16517     if (hasMFENCE(*Subtarget))
16518       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16519
16520     SDValue Chain = Op.getOperand(0);
16521     SDValue Zero = DAG.getConstant(0, MVT::i32);
16522     SDValue Ops[] = {
16523       DAG.getRegister(X86::ESP, MVT::i32), // Base
16524       DAG.getTargetConstant(1, MVT::i8),   // Scale
16525       DAG.getRegister(0, MVT::i32),        // Index
16526       DAG.getTargetConstant(0, MVT::i32),  // Disp
16527       DAG.getRegister(0, MVT::i32),        // Segment.
16528       Zero,
16529       Chain
16530     };
16531     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16532     return SDValue(Res, 0);
16533   }
16534
16535   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16536   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16537 }
16538
16539 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16540                              SelectionDAG &DAG) {
16541   MVT T = Op.getSimpleValueType();
16542   SDLoc DL(Op);
16543   unsigned Reg = 0;
16544   unsigned size = 0;
16545   switch(T.SimpleTy) {
16546   default: llvm_unreachable("Invalid value type!");
16547   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16548   case MVT::i16: Reg = X86::AX;  size = 2; break;
16549   case MVT::i32: Reg = X86::EAX; size = 4; break;
16550   case MVT::i64:
16551     assert(Subtarget->is64Bit() && "Node not type legal!");
16552     Reg = X86::RAX; size = 8;
16553     break;
16554   }
16555   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16556                                   Op.getOperand(2), SDValue());
16557   SDValue Ops[] = { cpIn.getValue(0),
16558                     Op.getOperand(1),
16559                     Op.getOperand(3),
16560                     DAG.getTargetConstant(size, MVT::i8),
16561                     cpIn.getValue(1) };
16562   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16563   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16564   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16565                                            Ops, T, MMO);
16566
16567   SDValue cpOut =
16568     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16569   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16570                                       MVT::i32, cpOut.getValue(2));
16571   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16572                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16573
16574   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16575   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16576   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16577   return SDValue();
16578 }
16579
16580 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16581                             SelectionDAG &DAG) {
16582   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16583   MVT DstVT = Op.getSimpleValueType();
16584
16585   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16586     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16587     if (DstVT != MVT::f64)
16588       // This conversion needs to be expanded.
16589       return SDValue();
16590
16591     SDValue InVec = Op->getOperand(0);
16592     SDLoc dl(Op);
16593     unsigned NumElts = SrcVT.getVectorNumElements();
16594     EVT SVT = SrcVT.getVectorElementType();
16595
16596     // Widen the vector in input in the case of MVT::v2i32.
16597     // Example: from MVT::v2i32 to MVT::v4i32.
16598     SmallVector<SDValue, 16> Elts;
16599     for (unsigned i = 0, e = NumElts; i != e; ++i)
16600       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16601                                  DAG.getIntPtrConstant(i)));
16602
16603     // Explicitly mark the extra elements as Undef.
16604     Elts.append(NumElts, DAG.getUNDEF(SVT));
16605
16606     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16607     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16608     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16609     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16610                        DAG.getIntPtrConstant(0));
16611   }
16612
16613   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16614          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16615   assert((DstVT == MVT::i64 ||
16616           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16617          "Unexpected custom BITCAST");
16618   // i64 <=> MMX conversions are Legal.
16619   if (SrcVT==MVT::i64 && DstVT.isVector())
16620     return Op;
16621   if (DstVT==MVT::i64 && SrcVT.isVector())
16622     return Op;
16623   // MMX <=> MMX conversions are Legal.
16624   if (SrcVT.isVector() && DstVT.isVector())
16625     return Op;
16626   // All other conversions need to be expanded.
16627   return SDValue();
16628 }
16629
16630 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16631                           SelectionDAG &DAG) {
16632   SDNode *Node = Op.getNode();
16633   SDLoc dl(Node);
16634
16635   Op = Op.getOperand(0);
16636   EVT VT = Op.getValueType();
16637   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16638          "CTPOP lowering only implemented for 128/256-bit wide vector types");
16639
16640   unsigned NumElts = VT.getVectorNumElements();
16641   EVT EltVT = VT.getVectorElementType();
16642   unsigned Len = EltVT.getSizeInBits();
16643
16644   // This is the vectorized version of the "best" algorithm from
16645   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16646   // with a minor tweak to use a series of adds + shifts instead of vector
16647   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16648   //
16649   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16650   //  v8i32 => Always profitable
16651   //
16652   // FIXME: There a couple of possible improvements:
16653   //
16654   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16655   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16656   //
16657   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16658          "CTPOP not implemented for this vector element type.");
16659
16660   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16661   // extra legalization.
16662   bool NeedsBitcast = EltVT == MVT::i32;
16663   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16664
16665   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16666   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16667   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16668
16669   // v = v - ((v >> 1) & 0x55555555...)
16670   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16671   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16672   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16673   if (NeedsBitcast)
16674     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16675
16676   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16677   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16678   if (NeedsBitcast)
16679     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16680
16681   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16682   if (VT != And.getValueType())
16683     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16684   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16685
16686   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16687   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16688   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16689   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16690   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16691
16692   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16693   if (NeedsBitcast) {
16694     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16695     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16696     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16697   }
16698
16699   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16700   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16701   if (VT != AndRHS.getValueType()) {
16702     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16703     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16704   }
16705   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16706
16707   // v = (v + (v >> 4)) & 0x0F0F0F0F...
16708   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16709   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16710   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16711   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16712
16713   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16714   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16715   if (NeedsBitcast) {
16716     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16717     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16718   }
16719   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16720   if (VT != And.getValueType())
16721     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16722
16723   // The algorithm mentioned above uses:
16724   //    v = (v * 0x01010101...) >> (Len - 8)
16725   //
16726   // Change it to use vector adds + vector shifts which yield faster results on
16727   // Haswell than using vector integer multiplication.
16728   //
16729   // For i32 elements:
16730   //    v = v + (v >> 8)
16731   //    v = v + (v >> 16)
16732   //
16733   // For i64 elements:
16734   //    v = v + (v >> 8)
16735   //    v = v + (v >> 16)
16736   //    v = v + (v >> 32)
16737   //
16738   Add = And;
16739   SmallVector<SDValue, 8> Csts;
16740   for (unsigned i = 8; i <= Len/2; i *= 2) {
16741     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16742     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16743     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16744     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16745     Csts.clear();
16746   }
16747
16748   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16749   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16750   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16751   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16752   if (NeedsBitcast) {
16753     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16754     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16755   }
16756   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16757   if (VT != And.getValueType())
16758     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16759
16760   return And;
16761 }
16762
16763 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16764   SDNode *Node = Op.getNode();
16765   SDLoc dl(Node);
16766   EVT T = Node->getValueType(0);
16767   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16768                               DAG.getConstant(0, T), Node->getOperand(2));
16769   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16770                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16771                        Node->getOperand(0),
16772                        Node->getOperand(1), negOp,
16773                        cast<AtomicSDNode>(Node)->getMemOperand(),
16774                        cast<AtomicSDNode>(Node)->getOrdering(),
16775                        cast<AtomicSDNode>(Node)->getSynchScope());
16776 }
16777
16778 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16779   SDNode *Node = Op.getNode();
16780   SDLoc dl(Node);
16781   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16782
16783   // Convert seq_cst store -> xchg
16784   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16785   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16786   //        (The only way to get a 16-byte store is cmpxchg16b)
16787   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16788   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16789       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16790     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16791                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16792                                  Node->getOperand(0),
16793                                  Node->getOperand(1), Node->getOperand(2),
16794                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16795                                  cast<AtomicSDNode>(Node)->getOrdering(),
16796                                  cast<AtomicSDNode>(Node)->getSynchScope());
16797     return Swap.getValue(1);
16798   }
16799   // Other atomic stores have a simple pattern.
16800   return Op;
16801 }
16802
16803 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16804   EVT VT = Op.getNode()->getSimpleValueType(0);
16805
16806   // Let legalize expand this if it isn't a legal type yet.
16807   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16808     return SDValue();
16809
16810   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16811
16812   unsigned Opc;
16813   bool ExtraOp = false;
16814   switch (Op.getOpcode()) {
16815   default: llvm_unreachable("Invalid code");
16816   case ISD::ADDC: Opc = X86ISD::ADD; break;
16817   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16818   case ISD::SUBC: Opc = X86ISD::SUB; break;
16819   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16820   }
16821
16822   if (!ExtraOp)
16823     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16824                        Op.getOperand(1));
16825   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16826                      Op.getOperand(1), Op.getOperand(2));
16827 }
16828
16829 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16830                             SelectionDAG &DAG) {
16831   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16832
16833   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16834   // which returns the values as { float, float } (in XMM0) or
16835   // { double, double } (which is returned in XMM0, XMM1).
16836   SDLoc dl(Op);
16837   SDValue Arg = Op.getOperand(0);
16838   EVT ArgVT = Arg.getValueType();
16839   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16840
16841   TargetLowering::ArgListTy Args;
16842   TargetLowering::ArgListEntry Entry;
16843
16844   Entry.Node = Arg;
16845   Entry.Ty = ArgTy;
16846   Entry.isSExt = false;
16847   Entry.isZExt = false;
16848   Args.push_back(Entry);
16849
16850   bool isF64 = ArgVT == MVT::f64;
16851   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16852   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16853   // the results are returned via SRet in memory.
16854   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16855   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16856   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16857
16858   Type *RetTy = isF64
16859     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
16860     : (Type*)VectorType::get(ArgTy, 4);
16861
16862   TargetLowering::CallLoweringInfo CLI(DAG);
16863   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16864     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16865
16866   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16867
16868   if (isF64)
16869     // Returned in xmm0 and xmm1.
16870     return CallResult.first;
16871
16872   // Returned in bits 0:31 and 32:64 xmm0.
16873   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16874                                CallResult.first, DAG.getIntPtrConstant(0));
16875   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16876                                CallResult.first, DAG.getIntPtrConstant(1));
16877   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16878   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16879 }
16880
16881 /// LowerOperation - Provide custom lowering hooks for some operations.
16882 ///
16883 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16884   switch (Op.getOpcode()) {
16885   default: llvm_unreachable("Should not custom lower this!");
16886   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16887   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16888     return LowerCMP_SWAP(Op, Subtarget, DAG);
16889   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
16890   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16891   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16892   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16893   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16894   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
16895   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16896   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16897   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16898   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16899   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16900   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16901   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16902   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16903   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16904   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16905   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16906   case ISD::SHL_PARTS:
16907   case ISD::SRA_PARTS:
16908   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16909   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16910   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16911   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16912   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16913   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16914   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16915   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16916   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16917   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16918   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16919   case ISD::FABS:
16920   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
16921   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16922   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16923   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16924   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16925   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16926   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16927   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16928   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16929   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16930   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
16931   case ISD::INTRINSIC_VOID:
16932   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16933   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16934   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16935   case ISD::FRAME_TO_ARGS_OFFSET:
16936                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16937   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16938   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16939   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16940   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16941   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16942   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16943   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16944   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16945   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16946   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16947   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16948   case ISD::UMUL_LOHI:
16949   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16950   case ISD::SRA:
16951   case ISD::SRL:
16952   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16953   case ISD::SADDO:
16954   case ISD::UADDO:
16955   case ISD::SSUBO:
16956   case ISD::USUBO:
16957   case ISD::SMULO:
16958   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16959   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16960   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16961   case ISD::ADDC:
16962   case ISD::ADDE:
16963   case ISD::SUBC:
16964   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16965   case ISD::ADD:                return LowerADD(Op, DAG);
16966   case ISD::SUB:                return LowerSUB(Op, DAG);
16967   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16968   }
16969 }
16970
16971 /// ReplaceNodeResults - Replace a node with an illegal result type
16972 /// with a new node built out of custom code.
16973 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16974                                            SmallVectorImpl<SDValue>&Results,
16975                                            SelectionDAG &DAG) const {
16976   SDLoc dl(N);
16977   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16978   switch (N->getOpcode()) {
16979   default:
16980     llvm_unreachable("Do not know how to custom type legalize this operation!");
16981   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
16982   case X86ISD::FMINC:
16983   case X86ISD::FMIN:
16984   case X86ISD::FMAXC:
16985   case X86ISD::FMAX: {
16986     EVT VT = N->getValueType(0);
16987     if (VT != MVT::v2f32)
16988       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
16989     SDValue UNDEF = DAG.getUNDEF(VT);
16990     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
16991                               N->getOperand(0), UNDEF);
16992     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
16993                               N->getOperand(1), UNDEF);
16994     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
16995     return;
16996   }
16997   case ISD::SIGN_EXTEND_INREG:
16998   case ISD::ADDC:
16999   case ISD::ADDE:
17000   case ISD::SUBC:
17001   case ISD::SUBE:
17002     // We don't want to expand or promote these.
17003     return;
17004   case ISD::SDIV:
17005   case ISD::UDIV:
17006   case ISD::SREM:
17007   case ISD::UREM:
17008   case ISD::SDIVREM:
17009   case ISD::UDIVREM: {
17010     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17011     Results.push_back(V);
17012     return;
17013   }
17014   case ISD::FP_TO_SINT:
17015   case ISD::FP_TO_UINT: {
17016     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17017
17018     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17019       return;
17020
17021     std::pair<SDValue,SDValue> Vals =
17022         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17023     SDValue FIST = Vals.first, StackSlot = Vals.second;
17024     if (FIST.getNode()) {
17025       EVT VT = N->getValueType(0);
17026       // Return a load from the stack slot.
17027       if (StackSlot.getNode())
17028         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17029                                       MachinePointerInfo(),
17030                                       false, false, false, 0));
17031       else
17032         Results.push_back(FIST);
17033     }
17034     return;
17035   }
17036   case ISD::UINT_TO_FP: {
17037     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17038     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17039         N->getValueType(0) != MVT::v2f32)
17040       return;
17041     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17042                                  N->getOperand(0));
17043     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17044                                      MVT::f64);
17045     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17046     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17047                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17048     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17049     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17050     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17051     return;
17052   }
17053   case ISD::FP_ROUND: {
17054     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17055         return;
17056     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17057     Results.push_back(V);
17058     return;
17059   }
17060   case ISD::INTRINSIC_W_CHAIN: {
17061     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17062     switch (IntNo) {
17063     default : llvm_unreachable("Do not know how to custom type "
17064                                "legalize this intrinsic operation!");
17065     case Intrinsic::x86_rdtsc:
17066       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17067                                      Results);
17068     case Intrinsic::x86_rdtscp:
17069       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17070                                      Results);
17071     case Intrinsic::x86_rdpmc:
17072       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17073     }
17074   }
17075   case ISD::READCYCLECOUNTER: {
17076     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17077                                    Results);
17078   }
17079   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17080     EVT T = N->getValueType(0);
17081     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17082     bool Regs64bit = T == MVT::i128;
17083     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17084     SDValue cpInL, cpInH;
17085     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17086                         DAG.getConstant(0, HalfT));
17087     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17088                         DAG.getConstant(1, HalfT));
17089     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17090                              Regs64bit ? X86::RAX : X86::EAX,
17091                              cpInL, SDValue());
17092     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17093                              Regs64bit ? X86::RDX : X86::EDX,
17094                              cpInH, cpInL.getValue(1));
17095     SDValue swapInL, swapInH;
17096     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17097                           DAG.getConstant(0, HalfT));
17098     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17099                           DAG.getConstant(1, HalfT));
17100     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17101                                Regs64bit ? X86::RBX : X86::EBX,
17102                                swapInL, cpInH.getValue(1));
17103     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17104                                Regs64bit ? X86::RCX : X86::ECX,
17105                                swapInH, swapInL.getValue(1));
17106     SDValue Ops[] = { swapInH.getValue(0),
17107                       N->getOperand(1),
17108                       swapInH.getValue(1) };
17109     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17110     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17111     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17112                                   X86ISD::LCMPXCHG8_DAG;
17113     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17114     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17115                                         Regs64bit ? X86::RAX : X86::EAX,
17116                                         HalfT, Result.getValue(1));
17117     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17118                                         Regs64bit ? X86::RDX : X86::EDX,
17119                                         HalfT, cpOutL.getValue(2));
17120     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17121
17122     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17123                                         MVT::i32, cpOutH.getValue(2));
17124     SDValue Success =
17125         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17126                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17127     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17128
17129     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17130     Results.push_back(Success);
17131     Results.push_back(EFLAGS.getValue(1));
17132     return;
17133   }
17134   case ISD::ATOMIC_SWAP:
17135   case ISD::ATOMIC_LOAD_ADD:
17136   case ISD::ATOMIC_LOAD_SUB:
17137   case ISD::ATOMIC_LOAD_AND:
17138   case ISD::ATOMIC_LOAD_OR:
17139   case ISD::ATOMIC_LOAD_XOR:
17140   case ISD::ATOMIC_LOAD_NAND:
17141   case ISD::ATOMIC_LOAD_MIN:
17142   case ISD::ATOMIC_LOAD_MAX:
17143   case ISD::ATOMIC_LOAD_UMIN:
17144   case ISD::ATOMIC_LOAD_UMAX:
17145   case ISD::ATOMIC_LOAD: {
17146     // Delegate to generic TypeLegalization. Situations we can really handle
17147     // should have already been dealt with by AtomicExpandPass.cpp.
17148     break;
17149   }
17150   case ISD::BITCAST: {
17151     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17152     EVT DstVT = N->getValueType(0);
17153     EVT SrcVT = N->getOperand(0)->getValueType(0);
17154
17155     if (SrcVT != MVT::f64 ||
17156         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17157       return;
17158
17159     unsigned NumElts = DstVT.getVectorNumElements();
17160     EVT SVT = DstVT.getVectorElementType();
17161     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17162     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17163                                    MVT::v2f64, N->getOperand(0));
17164     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17165
17166     if (ExperimentalVectorWideningLegalization) {
17167       // If we are legalizing vectors by widening, we already have the desired
17168       // legal vector type, just return it.
17169       Results.push_back(ToVecInt);
17170       return;
17171     }
17172
17173     SmallVector<SDValue, 8> Elts;
17174     for (unsigned i = 0, e = NumElts; i != e; ++i)
17175       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17176                                    ToVecInt, DAG.getIntPtrConstant(i)));
17177
17178     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17179   }
17180   }
17181 }
17182
17183 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17184   switch (Opcode) {
17185   default: return nullptr;
17186   case X86ISD::BSF:                return "X86ISD::BSF";
17187   case X86ISD::BSR:                return "X86ISD::BSR";
17188   case X86ISD::SHLD:               return "X86ISD::SHLD";
17189   case X86ISD::SHRD:               return "X86ISD::SHRD";
17190   case X86ISD::FAND:               return "X86ISD::FAND";
17191   case X86ISD::FANDN:              return "X86ISD::FANDN";
17192   case X86ISD::FOR:                return "X86ISD::FOR";
17193   case X86ISD::FXOR:               return "X86ISD::FXOR";
17194   case X86ISD::FSRL:               return "X86ISD::FSRL";
17195   case X86ISD::FILD:               return "X86ISD::FILD";
17196   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17197   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17198   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17199   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17200   case X86ISD::FLD:                return "X86ISD::FLD";
17201   case X86ISD::FST:                return "X86ISD::FST";
17202   case X86ISD::CALL:               return "X86ISD::CALL";
17203   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17204   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17205   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17206   case X86ISD::BT:                 return "X86ISD::BT";
17207   case X86ISD::CMP:                return "X86ISD::CMP";
17208   case X86ISD::COMI:               return "X86ISD::COMI";
17209   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17210   case X86ISD::CMPM:               return "X86ISD::CMPM";
17211   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17212   case X86ISD::SETCC:              return "X86ISD::SETCC";
17213   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17214   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17215   case X86ISD::CMOV:               return "X86ISD::CMOV";
17216   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17217   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17218   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17219   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17220   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17221   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17222   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17223   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17224   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17225   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17226   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17227   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17228   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17229   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17230   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17231   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17232   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17233   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17234   case X86ISD::HADD:               return "X86ISD::HADD";
17235   case X86ISD::HSUB:               return "X86ISD::HSUB";
17236   case X86ISD::FHADD:              return "X86ISD::FHADD";
17237   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17238   case X86ISD::UMAX:               return "X86ISD::UMAX";
17239   case X86ISD::UMIN:               return "X86ISD::UMIN";
17240   case X86ISD::SMAX:               return "X86ISD::SMAX";
17241   case X86ISD::SMIN:               return "X86ISD::SMIN";
17242   case X86ISD::FMAX:               return "X86ISD::FMAX";
17243   case X86ISD::FMIN:               return "X86ISD::FMIN";
17244   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17245   case X86ISD::FMINC:              return "X86ISD::FMINC";
17246   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17247   case X86ISD::FRCP:               return "X86ISD::FRCP";
17248   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17249   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17250   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17251   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17252   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17253   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17254   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17255   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17256   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17257   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17258   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17259   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17260   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17261   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17262   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17263   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17264   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17265   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17266   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17267   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17268   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17269   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17270   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17271   case X86ISD::VSHL:               return "X86ISD::VSHL";
17272   case X86ISD::VSRL:               return "X86ISD::VSRL";
17273   case X86ISD::VSRA:               return "X86ISD::VSRA";
17274   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17275   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17276   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17277   case X86ISD::CMPP:               return "X86ISD::CMPP";
17278   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17279   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17280   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17281   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17282   case X86ISD::ADD:                return "X86ISD::ADD";
17283   case X86ISD::SUB:                return "X86ISD::SUB";
17284   case X86ISD::ADC:                return "X86ISD::ADC";
17285   case X86ISD::SBB:                return "X86ISD::SBB";
17286   case X86ISD::SMUL:               return "X86ISD::SMUL";
17287   case X86ISD::UMUL:               return "X86ISD::UMUL";
17288   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17289   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17290   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17291   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17292   case X86ISD::INC:                return "X86ISD::INC";
17293   case X86ISD::DEC:                return "X86ISD::DEC";
17294   case X86ISD::OR:                 return "X86ISD::OR";
17295   case X86ISD::XOR:                return "X86ISD::XOR";
17296   case X86ISD::AND:                return "X86ISD::AND";
17297   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17298   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17299   case X86ISD::PTEST:              return "X86ISD::PTEST";
17300   case X86ISD::TESTP:              return "X86ISD::TESTP";
17301   case X86ISD::TESTM:              return "X86ISD::TESTM";
17302   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17303   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17304   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17305   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17306   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17307   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17308   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17309   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17310   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17311   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17312   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17313   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17314   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17315   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17316   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17317   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17318   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17319   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17320   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17321   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17322   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17323   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17324   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17325   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17326   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17327   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17328   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17329   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17330   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17331   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17332   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17333   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17334   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17335   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17336   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17337   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17338   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17339   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17340   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17341   case X86ISD::SAHF:               return "X86ISD::SAHF";
17342   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17343   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17344   case X86ISD::FMADD:              return "X86ISD::FMADD";
17345   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17346   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17347   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17348   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17349   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17350   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17351   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17352   case X86ISD::XTEST:              return "X86ISD::XTEST";
17353   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17354   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17355   case X86ISD::SELECT:             return "X86ISD::SELECT";
17356   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17357   case X86ISD::RCP28:              return "X86ISD::RCP28";
17358   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17359   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17360   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17361   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17362   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17363   }
17364 }
17365
17366 // isLegalAddressingMode - Return true if the addressing mode represented
17367 // by AM is legal for this target, for a load/store of the specified type.
17368 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17369                                               Type *Ty) const {
17370   // X86 supports extremely general addressing modes.
17371   CodeModel::Model M = getTargetMachine().getCodeModel();
17372   Reloc::Model R = getTargetMachine().getRelocationModel();
17373
17374   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17375   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17376     return false;
17377
17378   if (AM.BaseGV) {
17379     unsigned GVFlags =
17380       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17381
17382     // If a reference to this global requires an extra load, we can't fold it.
17383     if (isGlobalStubReference(GVFlags))
17384       return false;
17385
17386     // If BaseGV requires a register for the PIC base, we cannot also have a
17387     // BaseReg specified.
17388     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17389       return false;
17390
17391     // If lower 4G is not available, then we must use rip-relative addressing.
17392     if ((M != CodeModel::Small || R != Reloc::Static) &&
17393         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17394       return false;
17395   }
17396
17397   switch (AM.Scale) {
17398   case 0:
17399   case 1:
17400   case 2:
17401   case 4:
17402   case 8:
17403     // These scales always work.
17404     break;
17405   case 3:
17406   case 5:
17407   case 9:
17408     // These scales are formed with basereg+scalereg.  Only accept if there is
17409     // no basereg yet.
17410     if (AM.HasBaseReg)
17411       return false;
17412     break;
17413   default:  // Other stuff never works.
17414     return false;
17415   }
17416
17417   return true;
17418 }
17419
17420 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17421   unsigned Bits = Ty->getScalarSizeInBits();
17422
17423   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17424   // particularly cheaper than those without.
17425   if (Bits == 8)
17426     return false;
17427
17428   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17429   // variable shifts just as cheap as scalar ones.
17430   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17431     return false;
17432
17433   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17434   // fully general vector.
17435   return true;
17436 }
17437
17438 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17439   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17440     return false;
17441   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17442   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17443   return NumBits1 > NumBits2;
17444 }
17445
17446 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17447   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17448     return false;
17449
17450   if (!isTypeLegal(EVT::getEVT(Ty1)))
17451     return false;
17452
17453   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17454
17455   // Assuming the caller doesn't have a zeroext or signext return parameter,
17456   // truncation all the way down to i1 is valid.
17457   return true;
17458 }
17459
17460 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17461   return isInt<32>(Imm);
17462 }
17463
17464 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17465   // Can also use sub to handle negated immediates.
17466   return isInt<32>(Imm);
17467 }
17468
17469 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17470   if (!VT1.isInteger() || !VT2.isInteger())
17471     return false;
17472   unsigned NumBits1 = VT1.getSizeInBits();
17473   unsigned NumBits2 = VT2.getSizeInBits();
17474   return NumBits1 > NumBits2;
17475 }
17476
17477 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17478   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17479   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17480 }
17481
17482 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17483   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17484   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17485 }
17486
17487 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17488   EVT VT1 = Val.getValueType();
17489   if (isZExtFree(VT1, VT2))
17490     return true;
17491
17492   if (Val.getOpcode() != ISD::LOAD)
17493     return false;
17494
17495   if (!VT1.isSimple() || !VT1.isInteger() ||
17496       !VT2.isSimple() || !VT2.isInteger())
17497     return false;
17498
17499   switch (VT1.getSimpleVT().SimpleTy) {
17500   default: break;
17501   case MVT::i8:
17502   case MVT::i16:
17503   case MVT::i32:
17504     // X86 has 8, 16, and 32-bit zero-extending loads.
17505     return true;
17506   }
17507
17508   return false;
17509 }
17510
17511 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17512
17513 bool
17514 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17515   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17516     return false;
17517
17518   VT = VT.getScalarType();
17519
17520   if (!VT.isSimple())
17521     return false;
17522
17523   switch (VT.getSimpleVT().SimpleTy) {
17524   case MVT::f32:
17525   case MVT::f64:
17526     return true;
17527   default:
17528     break;
17529   }
17530
17531   return false;
17532 }
17533
17534 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17535   // i16 instructions are longer (0x66 prefix) and potentially slower.
17536   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17537 }
17538
17539 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17540 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17541 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17542 /// are assumed to be legal.
17543 bool
17544 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17545                                       EVT VT) const {
17546   if (!VT.isSimple())
17547     return false;
17548
17549   // Very little shuffling can be done for 64-bit vectors right now.
17550   if (VT.getSizeInBits() == 64)
17551     return false;
17552
17553   // We only care that the types being shuffled are legal. The lowering can
17554   // handle any possible shuffle mask that results.
17555   return isTypeLegal(VT.getSimpleVT());
17556 }
17557
17558 bool
17559 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17560                                           EVT VT) const {
17561   // Just delegate to the generic legality, clear masks aren't special.
17562   return isShuffleMaskLegal(Mask, VT);
17563 }
17564
17565 //===----------------------------------------------------------------------===//
17566 //                           X86 Scheduler Hooks
17567 //===----------------------------------------------------------------------===//
17568
17569 /// Utility function to emit xbegin specifying the start of an RTM region.
17570 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17571                                      const TargetInstrInfo *TII) {
17572   DebugLoc DL = MI->getDebugLoc();
17573
17574   const BasicBlock *BB = MBB->getBasicBlock();
17575   MachineFunction::iterator I = MBB;
17576   ++I;
17577
17578   // For the v = xbegin(), we generate
17579   //
17580   // thisMBB:
17581   //  xbegin sinkMBB
17582   //
17583   // mainMBB:
17584   //  eax = -1
17585   //
17586   // sinkMBB:
17587   //  v = eax
17588
17589   MachineBasicBlock *thisMBB = MBB;
17590   MachineFunction *MF = MBB->getParent();
17591   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17592   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17593   MF->insert(I, mainMBB);
17594   MF->insert(I, sinkMBB);
17595
17596   // Transfer the remainder of BB and its successor edges to sinkMBB.
17597   sinkMBB->splice(sinkMBB->begin(), MBB,
17598                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17599   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17600
17601   // thisMBB:
17602   //  xbegin sinkMBB
17603   //  # fallthrough to mainMBB
17604   //  # abortion to sinkMBB
17605   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17606   thisMBB->addSuccessor(mainMBB);
17607   thisMBB->addSuccessor(sinkMBB);
17608
17609   // mainMBB:
17610   //  EAX = -1
17611   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17612   mainMBB->addSuccessor(sinkMBB);
17613
17614   // sinkMBB:
17615   // EAX is live into the sinkMBB
17616   sinkMBB->addLiveIn(X86::EAX);
17617   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17618           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17619     .addReg(X86::EAX);
17620
17621   MI->eraseFromParent();
17622   return sinkMBB;
17623 }
17624
17625 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17626 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17627 // in the .td file.
17628 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17629                                        const TargetInstrInfo *TII) {
17630   unsigned Opc;
17631   switch (MI->getOpcode()) {
17632   default: llvm_unreachable("illegal opcode!");
17633   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17634   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17635   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17636   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17637   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17638   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17639   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17640   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17641   }
17642
17643   DebugLoc dl = MI->getDebugLoc();
17644   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17645
17646   unsigned NumArgs = MI->getNumOperands();
17647   for (unsigned i = 1; i < NumArgs; ++i) {
17648     MachineOperand &Op = MI->getOperand(i);
17649     if (!(Op.isReg() && Op.isImplicit()))
17650       MIB.addOperand(Op);
17651   }
17652   if (MI->hasOneMemOperand())
17653     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17654
17655   BuildMI(*BB, MI, dl,
17656     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17657     .addReg(X86::XMM0);
17658
17659   MI->eraseFromParent();
17660   return BB;
17661 }
17662
17663 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17664 // defs in an instruction pattern
17665 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17666                                        const TargetInstrInfo *TII) {
17667   unsigned Opc;
17668   switch (MI->getOpcode()) {
17669   default: llvm_unreachable("illegal opcode!");
17670   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17671   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17672   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17673   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17674   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17675   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17676   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17677   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17678   }
17679
17680   DebugLoc dl = MI->getDebugLoc();
17681   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17682
17683   unsigned NumArgs = MI->getNumOperands(); // remove the results
17684   for (unsigned i = 1; i < NumArgs; ++i) {
17685     MachineOperand &Op = MI->getOperand(i);
17686     if (!(Op.isReg() && Op.isImplicit()))
17687       MIB.addOperand(Op);
17688   }
17689   if (MI->hasOneMemOperand())
17690     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17691
17692   BuildMI(*BB, MI, dl,
17693     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17694     .addReg(X86::ECX);
17695
17696   MI->eraseFromParent();
17697   return BB;
17698 }
17699
17700 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17701                                       const X86Subtarget *Subtarget) {
17702   DebugLoc dl = MI->getDebugLoc();
17703   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17704   // Address into RAX/EAX, other two args into ECX, EDX.
17705   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17706   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17707   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17708   for (int i = 0; i < X86::AddrNumOperands; ++i)
17709     MIB.addOperand(MI->getOperand(i));
17710
17711   unsigned ValOps = X86::AddrNumOperands;
17712   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17713     .addReg(MI->getOperand(ValOps).getReg());
17714   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17715     .addReg(MI->getOperand(ValOps+1).getReg());
17716
17717   // The instruction doesn't actually take any operands though.
17718   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17719
17720   MI->eraseFromParent(); // The pseudo is gone now.
17721   return BB;
17722 }
17723
17724 MachineBasicBlock *
17725 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17726                                                  MachineBasicBlock *MBB) const {
17727   // Emit va_arg instruction on X86-64.
17728
17729   // Operands to this pseudo-instruction:
17730   // 0  ) Output        : destination address (reg)
17731   // 1-5) Input         : va_list address (addr, i64mem)
17732   // 6  ) ArgSize       : Size (in bytes) of vararg type
17733   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17734   // 8  ) Align         : Alignment of type
17735   // 9  ) EFLAGS (implicit-def)
17736
17737   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17738   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17739
17740   unsigned DestReg = MI->getOperand(0).getReg();
17741   MachineOperand &Base = MI->getOperand(1);
17742   MachineOperand &Scale = MI->getOperand(2);
17743   MachineOperand &Index = MI->getOperand(3);
17744   MachineOperand &Disp = MI->getOperand(4);
17745   MachineOperand &Segment = MI->getOperand(5);
17746   unsigned ArgSize = MI->getOperand(6).getImm();
17747   unsigned ArgMode = MI->getOperand(7).getImm();
17748   unsigned Align = MI->getOperand(8).getImm();
17749
17750   // Memory Reference
17751   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17752   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17753   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17754
17755   // Machine Information
17756   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17757   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17758   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17759   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17760   DebugLoc DL = MI->getDebugLoc();
17761
17762   // struct va_list {
17763   //   i32   gp_offset
17764   //   i32   fp_offset
17765   //   i64   overflow_area (address)
17766   //   i64   reg_save_area (address)
17767   // }
17768   // sizeof(va_list) = 24
17769   // alignment(va_list) = 8
17770
17771   unsigned TotalNumIntRegs = 6;
17772   unsigned TotalNumXMMRegs = 8;
17773   bool UseGPOffset = (ArgMode == 1);
17774   bool UseFPOffset = (ArgMode == 2);
17775   unsigned MaxOffset = TotalNumIntRegs * 8 +
17776                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17777
17778   /* Align ArgSize to a multiple of 8 */
17779   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17780   bool NeedsAlign = (Align > 8);
17781
17782   MachineBasicBlock *thisMBB = MBB;
17783   MachineBasicBlock *overflowMBB;
17784   MachineBasicBlock *offsetMBB;
17785   MachineBasicBlock *endMBB;
17786
17787   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17788   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17789   unsigned OffsetReg = 0;
17790
17791   if (!UseGPOffset && !UseFPOffset) {
17792     // If we only pull from the overflow region, we don't create a branch.
17793     // We don't need to alter control flow.
17794     OffsetDestReg = 0; // unused
17795     OverflowDestReg = DestReg;
17796
17797     offsetMBB = nullptr;
17798     overflowMBB = thisMBB;
17799     endMBB = thisMBB;
17800   } else {
17801     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17802     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17803     // If not, pull from overflow_area. (branch to overflowMBB)
17804     //
17805     //       thisMBB
17806     //         |     .
17807     //         |        .
17808     //     offsetMBB   overflowMBB
17809     //         |        .
17810     //         |     .
17811     //        endMBB
17812
17813     // Registers for the PHI in endMBB
17814     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17815     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17816
17817     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17818     MachineFunction *MF = MBB->getParent();
17819     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17820     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17821     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17822
17823     MachineFunction::iterator MBBIter = MBB;
17824     ++MBBIter;
17825
17826     // Insert the new basic blocks
17827     MF->insert(MBBIter, offsetMBB);
17828     MF->insert(MBBIter, overflowMBB);
17829     MF->insert(MBBIter, endMBB);
17830
17831     // Transfer the remainder of MBB and its successor edges to endMBB.
17832     endMBB->splice(endMBB->begin(), thisMBB,
17833                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17834     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17835
17836     // Make offsetMBB and overflowMBB successors of thisMBB
17837     thisMBB->addSuccessor(offsetMBB);
17838     thisMBB->addSuccessor(overflowMBB);
17839
17840     // endMBB is a successor of both offsetMBB and overflowMBB
17841     offsetMBB->addSuccessor(endMBB);
17842     overflowMBB->addSuccessor(endMBB);
17843
17844     // Load the offset value into a register
17845     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17846     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17847       .addOperand(Base)
17848       .addOperand(Scale)
17849       .addOperand(Index)
17850       .addDisp(Disp, UseFPOffset ? 4 : 0)
17851       .addOperand(Segment)
17852       .setMemRefs(MMOBegin, MMOEnd);
17853
17854     // Check if there is enough room left to pull this argument.
17855     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17856       .addReg(OffsetReg)
17857       .addImm(MaxOffset + 8 - ArgSizeA8);
17858
17859     // Branch to "overflowMBB" if offset >= max
17860     // Fall through to "offsetMBB" otherwise
17861     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17862       .addMBB(overflowMBB);
17863   }
17864
17865   // In offsetMBB, emit code to use the reg_save_area.
17866   if (offsetMBB) {
17867     assert(OffsetReg != 0);
17868
17869     // Read the reg_save_area address.
17870     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17871     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17872       .addOperand(Base)
17873       .addOperand(Scale)
17874       .addOperand(Index)
17875       .addDisp(Disp, 16)
17876       .addOperand(Segment)
17877       .setMemRefs(MMOBegin, MMOEnd);
17878
17879     // Zero-extend the offset
17880     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17881       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17882         .addImm(0)
17883         .addReg(OffsetReg)
17884         .addImm(X86::sub_32bit);
17885
17886     // Add the offset to the reg_save_area to get the final address.
17887     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17888       .addReg(OffsetReg64)
17889       .addReg(RegSaveReg);
17890
17891     // Compute the offset for the next argument
17892     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17893     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17894       .addReg(OffsetReg)
17895       .addImm(UseFPOffset ? 16 : 8);
17896
17897     // Store it back into the va_list.
17898     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17899       .addOperand(Base)
17900       .addOperand(Scale)
17901       .addOperand(Index)
17902       .addDisp(Disp, UseFPOffset ? 4 : 0)
17903       .addOperand(Segment)
17904       .addReg(NextOffsetReg)
17905       .setMemRefs(MMOBegin, MMOEnd);
17906
17907     // Jump to endMBB
17908     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
17909       .addMBB(endMBB);
17910   }
17911
17912   //
17913   // Emit code to use overflow area
17914   //
17915
17916   // Load the overflow_area address into a register.
17917   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17918   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17919     .addOperand(Base)
17920     .addOperand(Scale)
17921     .addOperand(Index)
17922     .addDisp(Disp, 8)
17923     .addOperand(Segment)
17924     .setMemRefs(MMOBegin, MMOEnd);
17925
17926   // If we need to align it, do so. Otherwise, just copy the address
17927   // to OverflowDestReg.
17928   if (NeedsAlign) {
17929     // Align the overflow address
17930     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17931     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17932
17933     // aligned_addr = (addr + (align-1)) & ~(align-1)
17934     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17935       .addReg(OverflowAddrReg)
17936       .addImm(Align-1);
17937
17938     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17939       .addReg(TmpReg)
17940       .addImm(~(uint64_t)(Align-1));
17941   } else {
17942     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17943       .addReg(OverflowAddrReg);
17944   }
17945
17946   // Compute the next overflow address after this argument.
17947   // (the overflow address should be kept 8-byte aligned)
17948   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17949   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17950     .addReg(OverflowDestReg)
17951     .addImm(ArgSizeA8);
17952
17953   // Store the new overflow address.
17954   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17955     .addOperand(Base)
17956     .addOperand(Scale)
17957     .addOperand(Index)
17958     .addDisp(Disp, 8)
17959     .addOperand(Segment)
17960     .addReg(NextAddrReg)
17961     .setMemRefs(MMOBegin, MMOEnd);
17962
17963   // If we branched, emit the PHI to the front of endMBB.
17964   if (offsetMBB) {
17965     BuildMI(*endMBB, endMBB->begin(), DL,
17966             TII->get(X86::PHI), DestReg)
17967       .addReg(OffsetDestReg).addMBB(offsetMBB)
17968       .addReg(OverflowDestReg).addMBB(overflowMBB);
17969   }
17970
17971   // Erase the pseudo instruction
17972   MI->eraseFromParent();
17973
17974   return endMBB;
17975 }
17976
17977 MachineBasicBlock *
17978 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17979                                                  MachineInstr *MI,
17980                                                  MachineBasicBlock *MBB) const {
17981   // Emit code to save XMM registers to the stack. The ABI says that the
17982   // number of registers to save is given in %al, so it's theoretically
17983   // possible to do an indirect jump trick to avoid saving all of them,
17984   // however this code takes a simpler approach and just executes all
17985   // of the stores if %al is non-zero. It's less code, and it's probably
17986   // easier on the hardware branch predictor, and stores aren't all that
17987   // expensive anyway.
17988
17989   // Create the new basic blocks. One block contains all the XMM stores,
17990   // and one block is the final destination regardless of whether any
17991   // stores were performed.
17992   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17993   MachineFunction *F = MBB->getParent();
17994   MachineFunction::iterator MBBIter = MBB;
17995   ++MBBIter;
17996   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17997   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17998   F->insert(MBBIter, XMMSaveMBB);
17999   F->insert(MBBIter, EndMBB);
18000
18001   // Transfer the remainder of MBB and its successor edges to EndMBB.
18002   EndMBB->splice(EndMBB->begin(), MBB,
18003                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18004   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18005
18006   // The original block will now fall through to the XMM save block.
18007   MBB->addSuccessor(XMMSaveMBB);
18008   // The XMMSaveMBB will fall through to the end block.
18009   XMMSaveMBB->addSuccessor(EndMBB);
18010
18011   // Now add the instructions.
18012   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18013   DebugLoc DL = MI->getDebugLoc();
18014
18015   unsigned CountReg = MI->getOperand(0).getReg();
18016   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18017   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18018
18019   if (!Subtarget->isTargetWin64()) {
18020     // If %al is 0, branch around the XMM save block.
18021     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18022     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18023     MBB->addSuccessor(EndMBB);
18024   }
18025
18026   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18027   // that was just emitted, but clearly shouldn't be "saved".
18028   assert((MI->getNumOperands() <= 3 ||
18029           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18030           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18031          && "Expected last argument to be EFLAGS");
18032   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18033   // In the XMM save block, save all the XMM argument registers.
18034   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18035     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18036     MachineMemOperand *MMO =
18037       F->getMachineMemOperand(
18038           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18039         MachineMemOperand::MOStore,
18040         /*Size=*/16, /*Align=*/16);
18041     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18042       .addFrameIndex(RegSaveFrameIndex)
18043       .addImm(/*Scale=*/1)
18044       .addReg(/*IndexReg=*/0)
18045       .addImm(/*Disp=*/Offset)
18046       .addReg(/*Segment=*/0)
18047       .addReg(MI->getOperand(i).getReg())
18048       .addMemOperand(MMO);
18049   }
18050
18051   MI->eraseFromParent();   // The pseudo instruction is gone now.
18052
18053   return EndMBB;
18054 }
18055
18056 // The EFLAGS operand of SelectItr might be missing a kill marker
18057 // because there were multiple uses of EFLAGS, and ISel didn't know
18058 // which to mark. Figure out whether SelectItr should have had a
18059 // kill marker, and set it if it should. Returns the correct kill
18060 // marker value.
18061 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18062                                      MachineBasicBlock* BB,
18063                                      const TargetRegisterInfo* TRI) {
18064   // Scan forward through BB for a use/def of EFLAGS.
18065   MachineBasicBlock::iterator miI(std::next(SelectItr));
18066   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18067     const MachineInstr& mi = *miI;
18068     if (mi.readsRegister(X86::EFLAGS))
18069       return false;
18070     if (mi.definesRegister(X86::EFLAGS))
18071       break; // Should have kill-flag - update below.
18072   }
18073
18074   // If we hit the end of the block, check whether EFLAGS is live into a
18075   // successor.
18076   if (miI == BB->end()) {
18077     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18078                                           sEnd = BB->succ_end();
18079          sItr != sEnd; ++sItr) {
18080       MachineBasicBlock* succ = *sItr;
18081       if (succ->isLiveIn(X86::EFLAGS))
18082         return false;
18083     }
18084   }
18085
18086   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18087   // out. SelectMI should have a kill flag on EFLAGS.
18088   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18089   return true;
18090 }
18091
18092 MachineBasicBlock *
18093 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18094                                      MachineBasicBlock *BB) const {
18095   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18096   DebugLoc DL = MI->getDebugLoc();
18097
18098   // To "insert" a SELECT_CC instruction, we actually have to insert the
18099   // diamond control-flow pattern.  The incoming instruction knows the
18100   // destination vreg to set, the condition code register to branch on, the
18101   // true/false values to select between, and a branch opcode to use.
18102   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18103   MachineFunction::iterator It = BB;
18104   ++It;
18105
18106   //  thisMBB:
18107   //  ...
18108   //   TrueVal = ...
18109   //   cmpTY ccX, r1, r2
18110   //   bCC copy1MBB
18111   //   fallthrough --> copy0MBB
18112   MachineBasicBlock *thisMBB = BB;
18113   MachineFunction *F = BB->getParent();
18114
18115   // We also lower double CMOVs:
18116   //   (CMOV (CMOV F, T, cc1), T, cc2)
18117   // to two successives branches.  For that, we look for another CMOV as the
18118   // following instruction.
18119   //
18120   // Without this, we would add a PHI between the two jumps, which ends up
18121   // creating a few copies all around. For instance, for
18122   //
18123   //    (sitofp (zext (fcmp une)))
18124   //
18125   // we would generate:
18126   //
18127   //         ucomiss %xmm1, %xmm0
18128   //         movss  <1.0f>, %xmm0
18129   //         movaps  %xmm0, %xmm1
18130   //         jne     .LBB5_2
18131   //         xorps   %xmm1, %xmm1
18132   // .LBB5_2:
18133   //         jp      .LBB5_4
18134   //         movaps  %xmm1, %xmm0
18135   // .LBB5_4:
18136   //         retq
18137   //
18138   // because this custom-inserter would have generated:
18139   //
18140   //   A
18141   //   | \
18142   //   |  B
18143   //   | /
18144   //   C
18145   //   | \
18146   //   |  D
18147   //   | /
18148   //   E
18149   //
18150   // A: X = ...; Y = ...
18151   // B: empty
18152   // C: Z = PHI [X, A], [Y, B]
18153   // D: empty
18154   // E: PHI [X, C], [Z, D]
18155   //
18156   // If we lower both CMOVs in a single step, we can instead generate:
18157   //
18158   //   A
18159   //   | \
18160   //   |  C
18161   //   | /|
18162   //   |/ |
18163   //   |  |
18164   //   |  D
18165   //   | /
18166   //   E
18167   //
18168   // A: X = ...; Y = ...
18169   // D: empty
18170   // E: PHI [X, A], [X, C], [Y, D]
18171   //
18172   // Which, in our sitofp/fcmp example, gives us something like:
18173   //
18174   //         ucomiss %xmm1, %xmm0
18175   //         movss  <1.0f>, %xmm0
18176   //         jne     .LBB5_4
18177   //         jp      .LBB5_4
18178   //         xorps   %xmm0, %xmm0
18179   // .LBB5_4:
18180   //         retq
18181   //
18182   MachineInstr *NextCMOV = nullptr;
18183   MachineBasicBlock::iterator NextMIIt =
18184       std::next(MachineBasicBlock::iterator(MI));
18185   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18186       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18187       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18188     NextCMOV = &*NextMIIt;
18189
18190   MachineBasicBlock *jcc1MBB = nullptr;
18191
18192   // If we have a double CMOV, we lower it to two successive branches to
18193   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18194   if (NextCMOV) {
18195     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18196     F->insert(It, jcc1MBB);
18197     jcc1MBB->addLiveIn(X86::EFLAGS);
18198   }
18199
18200   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18201   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18202   F->insert(It, copy0MBB);
18203   F->insert(It, sinkMBB);
18204
18205   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18206   // live into the sink and copy blocks.
18207   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18208
18209   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18210   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18211       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18212     copy0MBB->addLiveIn(X86::EFLAGS);
18213     sinkMBB->addLiveIn(X86::EFLAGS);
18214   }
18215
18216   // Transfer the remainder of BB and its successor edges to sinkMBB.
18217   sinkMBB->splice(sinkMBB->begin(), BB,
18218                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18219   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18220
18221   // Add the true and fallthrough blocks as its successors.
18222   if (NextCMOV) {
18223     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18224     BB->addSuccessor(jcc1MBB);
18225
18226     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18227     // jump to the sinkMBB.
18228     jcc1MBB->addSuccessor(copy0MBB);
18229     jcc1MBB->addSuccessor(sinkMBB);
18230   } else {
18231     BB->addSuccessor(copy0MBB);
18232   }
18233
18234   // The true block target of the first (or only) branch is always sinkMBB.
18235   BB->addSuccessor(sinkMBB);
18236
18237   // Create the conditional branch instruction.
18238   unsigned Opc =
18239     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18240   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18241
18242   if (NextCMOV) {
18243     unsigned Opc2 = X86::GetCondBranchFromCond(
18244         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18245     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18246   }
18247
18248   //  copy0MBB:
18249   //   %FalseValue = ...
18250   //   # fallthrough to sinkMBB
18251   copy0MBB->addSuccessor(sinkMBB);
18252
18253   //  sinkMBB:
18254   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18255   //  ...
18256   MachineInstrBuilder MIB =
18257       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18258               MI->getOperand(0).getReg())
18259           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18260           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18261
18262   // If we have a double CMOV, the second Jcc provides the same incoming
18263   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18264   if (NextCMOV) {
18265     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18266     // Copy the PHI result to the register defined by the second CMOV.
18267     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18268             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18269         .addReg(MI->getOperand(0).getReg());
18270     NextCMOV->eraseFromParent();
18271   }
18272
18273   MI->eraseFromParent();   // The pseudo instruction is gone now.
18274   return sinkMBB;
18275 }
18276
18277 MachineBasicBlock *
18278 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18279                                         MachineBasicBlock *BB) const {
18280   MachineFunction *MF = BB->getParent();
18281   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18282   DebugLoc DL = MI->getDebugLoc();
18283   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18284
18285   assert(MF->shouldSplitStack());
18286
18287   const bool Is64Bit = Subtarget->is64Bit();
18288   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18289
18290   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18291   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18292
18293   // BB:
18294   //  ... [Till the alloca]
18295   // If stacklet is not large enough, jump to mallocMBB
18296   //
18297   // bumpMBB:
18298   //  Allocate by subtracting from RSP
18299   //  Jump to continueMBB
18300   //
18301   // mallocMBB:
18302   //  Allocate by call to runtime
18303   //
18304   // continueMBB:
18305   //  ...
18306   //  [rest of original BB]
18307   //
18308
18309   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18310   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18311   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18312
18313   MachineRegisterInfo &MRI = MF->getRegInfo();
18314   const TargetRegisterClass *AddrRegClass =
18315     getRegClassFor(getPointerTy());
18316
18317   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18318     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18319     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18320     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18321     sizeVReg = MI->getOperand(1).getReg(),
18322     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18323
18324   MachineFunction::iterator MBBIter = BB;
18325   ++MBBIter;
18326
18327   MF->insert(MBBIter, bumpMBB);
18328   MF->insert(MBBIter, mallocMBB);
18329   MF->insert(MBBIter, continueMBB);
18330
18331   continueMBB->splice(continueMBB->begin(), BB,
18332                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18333   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18334
18335   // Add code to the main basic block to check if the stack limit has been hit,
18336   // and if so, jump to mallocMBB otherwise to bumpMBB.
18337   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18338   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18339     .addReg(tmpSPVReg).addReg(sizeVReg);
18340   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18341     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18342     .addReg(SPLimitVReg);
18343   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18344
18345   // bumpMBB simply decreases the stack pointer, since we know the current
18346   // stacklet has enough space.
18347   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18348     .addReg(SPLimitVReg);
18349   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18350     .addReg(SPLimitVReg);
18351   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18352
18353   // Calls into a routine in libgcc to allocate more space from the heap.
18354   const uint32_t *RegMask =
18355       Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18356   if (IsLP64) {
18357     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18358       .addReg(sizeVReg);
18359     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18360       .addExternalSymbol("__morestack_allocate_stack_space")
18361       .addRegMask(RegMask)
18362       .addReg(X86::RDI, RegState::Implicit)
18363       .addReg(X86::RAX, RegState::ImplicitDefine);
18364   } else if (Is64Bit) {
18365     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18366       .addReg(sizeVReg);
18367     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18368       .addExternalSymbol("__morestack_allocate_stack_space")
18369       .addRegMask(RegMask)
18370       .addReg(X86::EDI, RegState::Implicit)
18371       .addReg(X86::EAX, RegState::ImplicitDefine);
18372   } else {
18373     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18374       .addImm(12);
18375     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18376     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18377       .addExternalSymbol("__morestack_allocate_stack_space")
18378       .addRegMask(RegMask)
18379       .addReg(X86::EAX, RegState::ImplicitDefine);
18380   }
18381
18382   if (!Is64Bit)
18383     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18384       .addImm(16);
18385
18386   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18387     .addReg(IsLP64 ? X86::RAX : X86::EAX);
18388   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18389
18390   // Set up the CFG correctly.
18391   BB->addSuccessor(bumpMBB);
18392   BB->addSuccessor(mallocMBB);
18393   mallocMBB->addSuccessor(continueMBB);
18394   bumpMBB->addSuccessor(continueMBB);
18395
18396   // Take care of the PHI nodes.
18397   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18398           MI->getOperand(0).getReg())
18399     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18400     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18401
18402   // Delete the original pseudo instruction.
18403   MI->eraseFromParent();
18404
18405   // And we're done.
18406   return continueMBB;
18407 }
18408
18409 MachineBasicBlock *
18410 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18411                                         MachineBasicBlock *BB) const {
18412   DebugLoc DL = MI->getDebugLoc();
18413
18414   assert(!Subtarget->isTargetMachO());
18415
18416   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18417
18418   MI->eraseFromParent();   // The pseudo instruction is gone now.
18419   return BB;
18420 }
18421
18422 MachineBasicBlock *
18423 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18424                                       MachineBasicBlock *BB) const {
18425   // This is pretty easy.  We're taking the value that we received from
18426   // our load from the relocation, sticking it in either RDI (x86-64)
18427   // or EAX and doing an indirect call.  The return value will then
18428   // be in the normal return register.
18429   MachineFunction *F = BB->getParent();
18430   const X86InstrInfo *TII = Subtarget->getInstrInfo();
18431   DebugLoc DL = MI->getDebugLoc();
18432
18433   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18434   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18435
18436   // Get a register mask for the lowered call.
18437   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18438   // proper register mask.
18439   const uint32_t *RegMask =
18440       Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18441   if (Subtarget->is64Bit()) {
18442     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18443                                       TII->get(X86::MOV64rm), X86::RDI)
18444     .addReg(X86::RIP)
18445     .addImm(0).addReg(0)
18446     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18447                       MI->getOperand(3).getTargetFlags())
18448     .addReg(0);
18449     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18450     addDirectMem(MIB, X86::RDI);
18451     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18452   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18453     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18454                                       TII->get(X86::MOV32rm), X86::EAX)
18455     .addReg(0)
18456     .addImm(0).addReg(0)
18457     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18458                       MI->getOperand(3).getTargetFlags())
18459     .addReg(0);
18460     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18461     addDirectMem(MIB, X86::EAX);
18462     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18463   } else {
18464     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18465                                       TII->get(X86::MOV32rm), X86::EAX)
18466     .addReg(TII->getGlobalBaseReg(F))
18467     .addImm(0).addReg(0)
18468     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18469                       MI->getOperand(3).getTargetFlags())
18470     .addReg(0);
18471     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18472     addDirectMem(MIB, X86::EAX);
18473     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18474   }
18475
18476   MI->eraseFromParent(); // The pseudo instruction is gone now.
18477   return BB;
18478 }
18479
18480 MachineBasicBlock *
18481 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18482                                     MachineBasicBlock *MBB) const {
18483   DebugLoc DL = MI->getDebugLoc();
18484   MachineFunction *MF = MBB->getParent();
18485   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18486   MachineRegisterInfo &MRI = MF->getRegInfo();
18487
18488   const BasicBlock *BB = MBB->getBasicBlock();
18489   MachineFunction::iterator I = MBB;
18490   ++I;
18491
18492   // Memory Reference
18493   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18494   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18495
18496   unsigned DstReg;
18497   unsigned MemOpndSlot = 0;
18498
18499   unsigned CurOp = 0;
18500
18501   DstReg = MI->getOperand(CurOp++).getReg();
18502   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18503   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18504   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18505   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18506
18507   MemOpndSlot = CurOp;
18508
18509   MVT PVT = getPointerTy();
18510   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18511          "Invalid Pointer Size!");
18512
18513   // For v = setjmp(buf), we generate
18514   //
18515   // thisMBB:
18516   //  buf[LabelOffset] = restoreMBB
18517   //  SjLjSetup restoreMBB
18518   //
18519   // mainMBB:
18520   //  v_main = 0
18521   //
18522   // sinkMBB:
18523   //  v = phi(main, restore)
18524   //
18525   // restoreMBB:
18526   //  if base pointer being used, load it from frame
18527   //  v_restore = 1
18528
18529   MachineBasicBlock *thisMBB = MBB;
18530   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18531   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18532   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18533   MF->insert(I, mainMBB);
18534   MF->insert(I, sinkMBB);
18535   MF->push_back(restoreMBB);
18536
18537   MachineInstrBuilder MIB;
18538
18539   // Transfer the remainder of BB and its successor edges to sinkMBB.
18540   sinkMBB->splice(sinkMBB->begin(), MBB,
18541                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18542   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18543
18544   // thisMBB:
18545   unsigned PtrStoreOpc = 0;
18546   unsigned LabelReg = 0;
18547   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18548   Reloc::Model RM = MF->getTarget().getRelocationModel();
18549   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18550                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18551
18552   // Prepare IP either in reg or imm.
18553   if (!UseImmLabel) {
18554     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18555     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18556     LabelReg = MRI.createVirtualRegister(PtrRC);
18557     if (Subtarget->is64Bit()) {
18558       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18559               .addReg(X86::RIP)
18560               .addImm(0)
18561               .addReg(0)
18562               .addMBB(restoreMBB)
18563               .addReg(0);
18564     } else {
18565       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18566       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18567               .addReg(XII->getGlobalBaseReg(MF))
18568               .addImm(0)
18569               .addReg(0)
18570               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18571               .addReg(0);
18572     }
18573   } else
18574     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18575   // Store IP
18576   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18577   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18578     if (i == X86::AddrDisp)
18579       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18580     else
18581       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18582   }
18583   if (!UseImmLabel)
18584     MIB.addReg(LabelReg);
18585   else
18586     MIB.addMBB(restoreMBB);
18587   MIB.setMemRefs(MMOBegin, MMOEnd);
18588   // Setup
18589   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18590           .addMBB(restoreMBB);
18591
18592   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18593   MIB.addRegMask(RegInfo->getNoPreservedMask());
18594   thisMBB->addSuccessor(mainMBB);
18595   thisMBB->addSuccessor(restoreMBB);
18596
18597   // mainMBB:
18598   //  EAX = 0
18599   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18600   mainMBB->addSuccessor(sinkMBB);
18601
18602   // sinkMBB:
18603   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18604           TII->get(X86::PHI), DstReg)
18605     .addReg(mainDstReg).addMBB(mainMBB)
18606     .addReg(restoreDstReg).addMBB(restoreMBB);
18607
18608   // restoreMBB:
18609   if (RegInfo->hasBasePointer(*MF)) {
18610     const bool Uses64BitFramePtr =
18611         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18612     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18613     X86FI->setRestoreBasePointer(MF);
18614     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18615     unsigned BasePtr = RegInfo->getBaseRegister();
18616     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18617     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18618                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
18619       .setMIFlag(MachineInstr::FrameSetup);
18620   }
18621   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18622   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18623   restoreMBB->addSuccessor(sinkMBB);
18624
18625   MI->eraseFromParent();
18626   return sinkMBB;
18627 }
18628
18629 MachineBasicBlock *
18630 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18631                                      MachineBasicBlock *MBB) const {
18632   DebugLoc DL = MI->getDebugLoc();
18633   MachineFunction *MF = MBB->getParent();
18634   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18635   MachineRegisterInfo &MRI = MF->getRegInfo();
18636
18637   // Memory Reference
18638   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18639   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18640
18641   MVT PVT = getPointerTy();
18642   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18643          "Invalid Pointer Size!");
18644
18645   const TargetRegisterClass *RC =
18646     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18647   unsigned Tmp = MRI.createVirtualRegister(RC);
18648   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18649   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18650   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18651   unsigned SP = RegInfo->getStackRegister();
18652
18653   MachineInstrBuilder MIB;
18654
18655   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18656   const int64_t SPOffset = 2 * PVT.getStoreSize();
18657
18658   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18659   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18660
18661   // Reload FP
18662   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18663   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18664     MIB.addOperand(MI->getOperand(i));
18665   MIB.setMemRefs(MMOBegin, MMOEnd);
18666   // Reload IP
18667   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18668   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18669     if (i == X86::AddrDisp)
18670       MIB.addDisp(MI->getOperand(i), LabelOffset);
18671     else
18672       MIB.addOperand(MI->getOperand(i));
18673   }
18674   MIB.setMemRefs(MMOBegin, MMOEnd);
18675   // Reload SP
18676   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18677   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18678     if (i == X86::AddrDisp)
18679       MIB.addDisp(MI->getOperand(i), SPOffset);
18680     else
18681       MIB.addOperand(MI->getOperand(i));
18682   }
18683   MIB.setMemRefs(MMOBegin, MMOEnd);
18684   // Jump
18685   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18686
18687   MI->eraseFromParent();
18688   return MBB;
18689 }
18690
18691 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18692 // accumulator loops. Writing back to the accumulator allows the coalescer
18693 // to remove extra copies in the loop.
18694 MachineBasicBlock *
18695 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18696                                  MachineBasicBlock *MBB) const {
18697   MachineOperand &AddendOp = MI->getOperand(3);
18698
18699   // Bail out early if the addend isn't a register - we can't switch these.
18700   if (!AddendOp.isReg())
18701     return MBB;
18702
18703   MachineFunction &MF = *MBB->getParent();
18704   MachineRegisterInfo &MRI = MF.getRegInfo();
18705
18706   // Check whether the addend is defined by a PHI:
18707   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18708   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18709   if (!AddendDef.isPHI())
18710     return MBB;
18711
18712   // Look for the following pattern:
18713   // loop:
18714   //   %addend = phi [%entry, 0], [%loop, %result]
18715   //   ...
18716   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18717
18718   // Replace with:
18719   //   loop:
18720   //   %addend = phi [%entry, 0], [%loop, %result]
18721   //   ...
18722   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18723
18724   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18725     assert(AddendDef.getOperand(i).isReg());
18726     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18727     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18728     if (&PHISrcInst == MI) {
18729       // Found a matching instruction.
18730       unsigned NewFMAOpc = 0;
18731       switch (MI->getOpcode()) {
18732         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18733         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18734         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18735         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18736         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18737         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18738         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18739         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18740         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18741         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18742         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18743         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18744         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18745         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18746         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18747         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18748         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18749         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18750         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18751         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18752
18753         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18754         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18755         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18756         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18757         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18758         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18759         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18760         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18761         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18762         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18763         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18764         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18765         default: llvm_unreachable("Unrecognized FMA variant.");
18766       }
18767
18768       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18769       MachineInstrBuilder MIB =
18770         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18771         .addOperand(MI->getOperand(0))
18772         .addOperand(MI->getOperand(3))
18773         .addOperand(MI->getOperand(2))
18774         .addOperand(MI->getOperand(1));
18775       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18776       MI->eraseFromParent();
18777     }
18778   }
18779
18780   return MBB;
18781 }
18782
18783 MachineBasicBlock *
18784 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18785                                                MachineBasicBlock *BB) const {
18786   switch (MI->getOpcode()) {
18787   default: llvm_unreachable("Unexpected instr type to insert");
18788   case X86::TAILJMPd64:
18789   case X86::TAILJMPr64:
18790   case X86::TAILJMPm64:
18791   case X86::TAILJMPd64_REX:
18792   case X86::TAILJMPr64_REX:
18793   case X86::TAILJMPm64_REX:
18794     llvm_unreachable("TAILJMP64 would not be touched here.");
18795   case X86::TCRETURNdi64:
18796   case X86::TCRETURNri64:
18797   case X86::TCRETURNmi64:
18798     return BB;
18799   case X86::WIN_ALLOCA:
18800     return EmitLoweredWinAlloca(MI, BB);
18801   case X86::SEG_ALLOCA_32:
18802   case X86::SEG_ALLOCA_64:
18803     return EmitLoweredSegAlloca(MI, BB);
18804   case X86::TLSCall_32:
18805   case X86::TLSCall_64:
18806     return EmitLoweredTLSCall(MI, BB);
18807   case X86::CMOV_GR8:
18808   case X86::CMOV_FR32:
18809   case X86::CMOV_FR64:
18810   case X86::CMOV_V4F32:
18811   case X86::CMOV_V2F64:
18812   case X86::CMOV_V2I64:
18813   case X86::CMOV_V8F32:
18814   case X86::CMOV_V4F64:
18815   case X86::CMOV_V4I64:
18816   case X86::CMOV_V16F32:
18817   case X86::CMOV_V8F64:
18818   case X86::CMOV_V8I64:
18819   case X86::CMOV_GR16:
18820   case X86::CMOV_GR32:
18821   case X86::CMOV_RFP32:
18822   case X86::CMOV_RFP64:
18823   case X86::CMOV_RFP80:
18824     return EmitLoweredSelect(MI, BB);
18825
18826   case X86::FP32_TO_INT16_IN_MEM:
18827   case X86::FP32_TO_INT32_IN_MEM:
18828   case X86::FP32_TO_INT64_IN_MEM:
18829   case X86::FP64_TO_INT16_IN_MEM:
18830   case X86::FP64_TO_INT32_IN_MEM:
18831   case X86::FP64_TO_INT64_IN_MEM:
18832   case X86::FP80_TO_INT16_IN_MEM:
18833   case X86::FP80_TO_INT32_IN_MEM:
18834   case X86::FP80_TO_INT64_IN_MEM: {
18835     MachineFunction *F = BB->getParent();
18836     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18837     DebugLoc DL = MI->getDebugLoc();
18838
18839     // Change the floating point control register to use "round towards zero"
18840     // mode when truncating to an integer value.
18841     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18842     addFrameReference(BuildMI(*BB, MI, DL,
18843                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18844
18845     // Load the old value of the high byte of the control word...
18846     unsigned OldCW =
18847       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18848     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18849                       CWFrameIdx);
18850
18851     // Set the high part to be round to zero...
18852     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18853       .addImm(0xC7F);
18854
18855     // Reload the modified control word now...
18856     addFrameReference(BuildMI(*BB, MI, DL,
18857                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18858
18859     // Restore the memory image of control word to original value
18860     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18861       .addReg(OldCW);
18862
18863     // Get the X86 opcode to use.
18864     unsigned Opc;
18865     switch (MI->getOpcode()) {
18866     default: llvm_unreachable("illegal opcode!");
18867     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18868     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18869     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18870     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18871     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18872     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18873     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18874     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18875     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18876     }
18877
18878     X86AddressMode AM;
18879     MachineOperand &Op = MI->getOperand(0);
18880     if (Op.isReg()) {
18881       AM.BaseType = X86AddressMode::RegBase;
18882       AM.Base.Reg = Op.getReg();
18883     } else {
18884       AM.BaseType = X86AddressMode::FrameIndexBase;
18885       AM.Base.FrameIndex = Op.getIndex();
18886     }
18887     Op = MI->getOperand(1);
18888     if (Op.isImm())
18889       AM.Scale = Op.getImm();
18890     Op = MI->getOperand(2);
18891     if (Op.isImm())
18892       AM.IndexReg = Op.getImm();
18893     Op = MI->getOperand(3);
18894     if (Op.isGlobal()) {
18895       AM.GV = Op.getGlobal();
18896     } else {
18897       AM.Disp = Op.getImm();
18898     }
18899     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18900                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18901
18902     // Reload the original control word now.
18903     addFrameReference(BuildMI(*BB, MI, DL,
18904                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18905
18906     MI->eraseFromParent();   // The pseudo instruction is gone now.
18907     return BB;
18908   }
18909     // String/text processing lowering.
18910   case X86::PCMPISTRM128REG:
18911   case X86::VPCMPISTRM128REG:
18912   case X86::PCMPISTRM128MEM:
18913   case X86::VPCMPISTRM128MEM:
18914   case X86::PCMPESTRM128REG:
18915   case X86::VPCMPESTRM128REG:
18916   case X86::PCMPESTRM128MEM:
18917   case X86::VPCMPESTRM128MEM:
18918     assert(Subtarget->hasSSE42() &&
18919            "Target must have SSE4.2 or AVX features enabled");
18920     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
18921
18922   // String/text processing lowering.
18923   case X86::PCMPISTRIREG:
18924   case X86::VPCMPISTRIREG:
18925   case X86::PCMPISTRIMEM:
18926   case X86::VPCMPISTRIMEM:
18927   case X86::PCMPESTRIREG:
18928   case X86::VPCMPESTRIREG:
18929   case X86::PCMPESTRIMEM:
18930   case X86::VPCMPESTRIMEM:
18931     assert(Subtarget->hasSSE42() &&
18932            "Target must have SSE4.2 or AVX features enabled");
18933     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
18934
18935   // Thread synchronization.
18936   case X86::MONITOR:
18937     return EmitMonitor(MI, BB, Subtarget);
18938
18939   // xbegin
18940   case X86::XBEGIN:
18941     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
18942
18943   case X86::VASTART_SAVE_XMM_REGS:
18944     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18945
18946   case X86::VAARG_64:
18947     return EmitVAARG64WithCustomInserter(MI, BB);
18948
18949   case X86::EH_SjLj_SetJmp32:
18950   case X86::EH_SjLj_SetJmp64:
18951     return emitEHSjLjSetJmp(MI, BB);
18952
18953   case X86::EH_SjLj_LongJmp32:
18954   case X86::EH_SjLj_LongJmp64:
18955     return emitEHSjLjLongJmp(MI, BB);
18956
18957   case TargetOpcode::STATEPOINT:
18958     // As an implementation detail, STATEPOINT shares the STACKMAP format at
18959     // this point in the process.  We diverge later.
18960     return emitPatchPoint(MI, BB);
18961
18962   case TargetOpcode::STACKMAP:
18963   case TargetOpcode::PATCHPOINT:
18964     return emitPatchPoint(MI, BB);
18965
18966   case X86::VFMADDPDr213r:
18967   case X86::VFMADDPSr213r:
18968   case X86::VFMADDSDr213r:
18969   case X86::VFMADDSSr213r:
18970   case X86::VFMSUBPDr213r:
18971   case X86::VFMSUBPSr213r:
18972   case X86::VFMSUBSDr213r:
18973   case X86::VFMSUBSSr213r:
18974   case X86::VFNMADDPDr213r:
18975   case X86::VFNMADDPSr213r:
18976   case X86::VFNMADDSDr213r:
18977   case X86::VFNMADDSSr213r:
18978   case X86::VFNMSUBPDr213r:
18979   case X86::VFNMSUBPSr213r:
18980   case X86::VFNMSUBSDr213r:
18981   case X86::VFNMSUBSSr213r:
18982   case X86::VFMADDSUBPDr213r:
18983   case X86::VFMADDSUBPSr213r:
18984   case X86::VFMSUBADDPDr213r:
18985   case X86::VFMSUBADDPSr213r:
18986   case X86::VFMADDPDr213rY:
18987   case X86::VFMADDPSr213rY:
18988   case X86::VFMSUBPDr213rY:
18989   case X86::VFMSUBPSr213rY:
18990   case X86::VFNMADDPDr213rY:
18991   case X86::VFNMADDPSr213rY:
18992   case X86::VFNMSUBPDr213rY:
18993   case X86::VFNMSUBPSr213rY:
18994   case X86::VFMADDSUBPDr213rY:
18995   case X86::VFMADDSUBPSr213rY:
18996   case X86::VFMSUBADDPDr213rY:
18997   case X86::VFMSUBADDPSr213rY:
18998     return emitFMA3Instr(MI, BB);
18999   }
19000 }
19001
19002 //===----------------------------------------------------------------------===//
19003 //                           X86 Optimization Hooks
19004 //===----------------------------------------------------------------------===//
19005
19006 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19007                                                       APInt &KnownZero,
19008                                                       APInt &KnownOne,
19009                                                       const SelectionDAG &DAG,
19010                                                       unsigned Depth) const {
19011   unsigned BitWidth = KnownZero.getBitWidth();
19012   unsigned Opc = Op.getOpcode();
19013   assert((Opc >= ISD::BUILTIN_OP_END ||
19014           Opc == ISD::INTRINSIC_WO_CHAIN ||
19015           Opc == ISD::INTRINSIC_W_CHAIN ||
19016           Opc == ISD::INTRINSIC_VOID) &&
19017          "Should use MaskedValueIsZero if you don't know whether Op"
19018          " is a target node!");
19019
19020   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19021   switch (Opc) {
19022   default: break;
19023   case X86ISD::ADD:
19024   case X86ISD::SUB:
19025   case X86ISD::ADC:
19026   case X86ISD::SBB:
19027   case X86ISD::SMUL:
19028   case X86ISD::UMUL:
19029   case X86ISD::INC:
19030   case X86ISD::DEC:
19031   case X86ISD::OR:
19032   case X86ISD::XOR:
19033   case X86ISD::AND:
19034     // These nodes' second result is a boolean.
19035     if (Op.getResNo() == 0)
19036       break;
19037     // Fallthrough
19038   case X86ISD::SETCC:
19039     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19040     break;
19041   case ISD::INTRINSIC_WO_CHAIN: {
19042     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19043     unsigned NumLoBits = 0;
19044     switch (IntId) {
19045     default: break;
19046     case Intrinsic::x86_sse_movmsk_ps:
19047     case Intrinsic::x86_avx_movmsk_ps_256:
19048     case Intrinsic::x86_sse2_movmsk_pd:
19049     case Intrinsic::x86_avx_movmsk_pd_256:
19050     case Intrinsic::x86_mmx_pmovmskb:
19051     case Intrinsic::x86_sse2_pmovmskb_128:
19052     case Intrinsic::x86_avx2_pmovmskb: {
19053       // High bits of movmskp{s|d}, pmovmskb are known zero.
19054       switch (IntId) {
19055         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19056         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19057         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19058         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19059         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19060         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19061         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19062         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19063       }
19064       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19065       break;
19066     }
19067     }
19068     break;
19069   }
19070   }
19071 }
19072
19073 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19074   SDValue Op,
19075   const SelectionDAG &,
19076   unsigned Depth) const {
19077   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19078   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19079     return Op.getValueType().getScalarType().getSizeInBits();
19080
19081   // Fallback case.
19082   return 1;
19083 }
19084
19085 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19086 /// node is a GlobalAddress + offset.
19087 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19088                                        const GlobalValue* &GA,
19089                                        int64_t &Offset) const {
19090   if (N->getOpcode() == X86ISD::Wrapper) {
19091     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19092       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19093       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19094       return true;
19095     }
19096   }
19097   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19098 }
19099
19100 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19101 /// same as extracting the high 128-bit part of 256-bit vector and then
19102 /// inserting the result into the low part of a new 256-bit vector
19103 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19104   EVT VT = SVOp->getValueType(0);
19105   unsigned NumElems = VT.getVectorNumElements();
19106
19107   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19108   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19109     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19110         SVOp->getMaskElt(j) >= 0)
19111       return false;
19112
19113   return true;
19114 }
19115
19116 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19117 /// same as extracting the low 128-bit part of 256-bit vector and then
19118 /// inserting the result into the high part of a new 256-bit vector
19119 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19120   EVT VT = SVOp->getValueType(0);
19121   unsigned NumElems = VT.getVectorNumElements();
19122
19123   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19124   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19125     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19126         SVOp->getMaskElt(j) >= 0)
19127       return false;
19128
19129   return true;
19130 }
19131
19132 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19133 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19134                                         TargetLowering::DAGCombinerInfo &DCI,
19135                                         const X86Subtarget* Subtarget) {
19136   SDLoc dl(N);
19137   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19138   SDValue V1 = SVOp->getOperand(0);
19139   SDValue V2 = SVOp->getOperand(1);
19140   EVT VT = SVOp->getValueType(0);
19141   unsigned NumElems = VT.getVectorNumElements();
19142
19143   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19144       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19145     //
19146     //                   0,0,0,...
19147     //                      |
19148     //    V      UNDEF    BUILD_VECTOR    UNDEF
19149     //     \      /           \           /
19150     //  CONCAT_VECTOR         CONCAT_VECTOR
19151     //         \                  /
19152     //          \                /
19153     //          RESULT: V + zero extended
19154     //
19155     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19156         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19157         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19158       return SDValue();
19159
19160     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19161       return SDValue();
19162
19163     // To match the shuffle mask, the first half of the mask should
19164     // be exactly the first vector, and all the rest a splat with the
19165     // first element of the second one.
19166     for (unsigned i = 0; i != NumElems/2; ++i)
19167       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19168           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19169         return SDValue();
19170
19171     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19172     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19173       if (Ld->hasNUsesOfValue(1, 0)) {
19174         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19175         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19176         SDValue ResNode =
19177           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19178                                   Ld->getMemoryVT(),
19179                                   Ld->getPointerInfo(),
19180                                   Ld->getAlignment(),
19181                                   false/*isVolatile*/, true/*ReadMem*/,
19182                                   false/*WriteMem*/);
19183
19184         // Make sure the newly-created LOAD is in the same position as Ld in
19185         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19186         // and update uses of Ld's output chain to use the TokenFactor.
19187         if (Ld->hasAnyUseOfValue(1)) {
19188           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19189                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19190           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19191           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19192                                  SDValue(ResNode.getNode(), 1));
19193         }
19194
19195         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19196       }
19197     }
19198
19199     // Emit a zeroed vector and insert the desired subvector on its
19200     // first half.
19201     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19202     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19203     return DCI.CombineTo(N, InsV);
19204   }
19205
19206   //===--------------------------------------------------------------------===//
19207   // Combine some shuffles into subvector extracts and inserts:
19208   //
19209
19210   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19211   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19212     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19213     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19214     return DCI.CombineTo(N, InsV);
19215   }
19216
19217   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19218   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19219     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19220     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19221     return DCI.CombineTo(N, InsV);
19222   }
19223
19224   return SDValue();
19225 }
19226
19227 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19228 /// possible.
19229 ///
19230 /// This is the leaf of the recursive combinine below. When we have found some
19231 /// chain of single-use x86 shuffle instructions and accumulated the combined
19232 /// shuffle mask represented by them, this will try to pattern match that mask
19233 /// into either a single instruction if there is a special purpose instruction
19234 /// for this operation, or into a PSHUFB instruction which is a fully general
19235 /// instruction but should only be used to replace chains over a certain depth.
19236 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19237                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19238                                    TargetLowering::DAGCombinerInfo &DCI,
19239                                    const X86Subtarget *Subtarget) {
19240   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19241
19242   // Find the operand that enters the chain. Note that multiple uses are OK
19243   // here, we're not going to remove the operand we find.
19244   SDValue Input = Op.getOperand(0);
19245   while (Input.getOpcode() == ISD::BITCAST)
19246     Input = Input.getOperand(0);
19247
19248   MVT VT = Input.getSimpleValueType();
19249   MVT RootVT = Root.getSimpleValueType();
19250   SDLoc DL(Root);
19251
19252   // Just remove no-op shuffle masks.
19253   if (Mask.size() == 1) {
19254     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19255                   /*AddTo*/ true);
19256     return true;
19257   }
19258
19259   // Use the float domain if the operand type is a floating point type.
19260   bool FloatDomain = VT.isFloatingPoint();
19261
19262   // For floating point shuffles, we don't have free copies in the shuffle
19263   // instructions or the ability to load as part of the instruction, so
19264   // canonicalize their shuffles to UNPCK or MOV variants.
19265   //
19266   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19267   // vectors because it can have a load folded into it that UNPCK cannot. This
19268   // doesn't preclude something switching to the shorter encoding post-RA.
19269   //
19270   // FIXME: Should teach these routines about AVX vector widths.
19271   if (FloatDomain && VT.getSizeInBits() == 128) {
19272     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19273       bool Lo = Mask.equals({0, 0});
19274       unsigned Shuffle;
19275       MVT ShuffleVT;
19276       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19277       // is no slower than UNPCKLPD but has the option to fold the input operand
19278       // into even an unaligned memory load.
19279       if (Lo && Subtarget->hasSSE3()) {
19280         Shuffle = X86ISD::MOVDDUP;
19281         ShuffleVT = MVT::v2f64;
19282       } else {
19283         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19284         // than the UNPCK variants.
19285         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19286         ShuffleVT = MVT::v4f32;
19287       }
19288       if (Depth == 1 && Root->getOpcode() == Shuffle)
19289         return false; // Nothing to do!
19290       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19291       DCI.AddToWorklist(Op.getNode());
19292       if (Shuffle == X86ISD::MOVDDUP)
19293         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19294       else
19295         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19296       DCI.AddToWorklist(Op.getNode());
19297       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19298                     /*AddTo*/ true);
19299       return true;
19300     }
19301     if (Subtarget->hasSSE3() &&
19302         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19303       bool Lo = Mask.equals({0, 0, 2, 2});
19304       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19305       MVT ShuffleVT = MVT::v4f32;
19306       if (Depth == 1 && Root->getOpcode() == Shuffle)
19307         return false; // Nothing to do!
19308       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19309       DCI.AddToWorklist(Op.getNode());
19310       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19311       DCI.AddToWorklist(Op.getNode());
19312       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19313                     /*AddTo*/ true);
19314       return true;
19315     }
19316     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19317       bool Lo = Mask.equals({0, 0, 1, 1});
19318       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19319       MVT ShuffleVT = MVT::v4f32;
19320       if (Depth == 1 && Root->getOpcode() == Shuffle)
19321         return false; // Nothing to do!
19322       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19323       DCI.AddToWorklist(Op.getNode());
19324       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19325       DCI.AddToWorklist(Op.getNode());
19326       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19327                     /*AddTo*/ true);
19328       return true;
19329     }
19330   }
19331
19332   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19333   // variants as none of these have single-instruction variants that are
19334   // superior to the UNPCK formulation.
19335   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19336       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19337        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19338        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19339        Mask.equals(
19340            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19341     bool Lo = Mask[0] == 0;
19342     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19343     if (Depth == 1 && Root->getOpcode() == Shuffle)
19344       return false; // Nothing to do!
19345     MVT ShuffleVT;
19346     switch (Mask.size()) {
19347     case 8:
19348       ShuffleVT = MVT::v8i16;
19349       break;
19350     case 16:
19351       ShuffleVT = MVT::v16i8;
19352       break;
19353     default:
19354       llvm_unreachable("Impossible mask size!");
19355     };
19356     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19357     DCI.AddToWorklist(Op.getNode());
19358     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19359     DCI.AddToWorklist(Op.getNode());
19360     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19361                   /*AddTo*/ true);
19362     return true;
19363   }
19364
19365   // Don't try to re-form single instruction chains under any circumstances now
19366   // that we've done encoding canonicalization for them.
19367   if (Depth < 2)
19368     return false;
19369
19370   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19371   // can replace them with a single PSHUFB instruction profitably. Intel's
19372   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19373   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19374   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19375     SmallVector<SDValue, 16> PSHUFBMask;
19376     int NumBytes = VT.getSizeInBits() / 8;
19377     int Ratio = NumBytes / Mask.size();
19378     for (int i = 0; i < NumBytes; ++i) {
19379       if (Mask[i / Ratio] == SM_SentinelUndef) {
19380         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19381         continue;
19382       }
19383       int M = Mask[i / Ratio] != SM_SentinelZero
19384                   ? Ratio * Mask[i / Ratio] + i % Ratio
19385                   : 255;
19386       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19387     }
19388     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19389     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19390     DCI.AddToWorklist(Op.getNode());
19391     SDValue PSHUFBMaskOp =
19392         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19393     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19394     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19395     DCI.AddToWorklist(Op.getNode());
19396     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19397                   /*AddTo*/ true);
19398     return true;
19399   }
19400
19401   // Failed to find any combines.
19402   return false;
19403 }
19404
19405 /// \brief Fully generic combining of x86 shuffle instructions.
19406 ///
19407 /// This should be the last combine run over the x86 shuffle instructions. Once
19408 /// they have been fully optimized, this will recursively consider all chains
19409 /// of single-use shuffle instructions, build a generic model of the cumulative
19410 /// shuffle operation, and check for simpler instructions which implement this
19411 /// operation. We use this primarily for two purposes:
19412 ///
19413 /// 1) Collapse generic shuffles to specialized single instructions when
19414 ///    equivalent. In most cases, this is just an encoding size win, but
19415 ///    sometimes we will collapse multiple generic shuffles into a single
19416 ///    special-purpose shuffle.
19417 /// 2) Look for sequences of shuffle instructions with 3 or more total
19418 ///    instructions, and replace them with the slightly more expensive SSSE3
19419 ///    PSHUFB instruction if available. We do this as the last combining step
19420 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19421 ///    a suitable short sequence of other instructions. The PHUFB will either
19422 ///    use a register or have to read from memory and so is slightly (but only
19423 ///    slightly) more expensive than the other shuffle instructions.
19424 ///
19425 /// Because this is inherently a quadratic operation (for each shuffle in
19426 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19427 /// This should never be an issue in practice as the shuffle lowering doesn't
19428 /// produce sequences of more than 8 instructions.
19429 ///
19430 /// FIXME: We will currently miss some cases where the redundant shuffling
19431 /// would simplify under the threshold for PSHUFB formation because of
19432 /// combine-ordering. To fix this, we should do the redundant instruction
19433 /// combining in this recursive walk.
19434 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19435                                           ArrayRef<int> RootMask,
19436                                           int Depth, bool HasPSHUFB,
19437                                           SelectionDAG &DAG,
19438                                           TargetLowering::DAGCombinerInfo &DCI,
19439                                           const X86Subtarget *Subtarget) {
19440   // Bound the depth of our recursive combine because this is ultimately
19441   // quadratic in nature.
19442   if (Depth > 8)
19443     return false;
19444
19445   // Directly rip through bitcasts to find the underlying operand.
19446   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19447     Op = Op.getOperand(0);
19448
19449   MVT VT = Op.getSimpleValueType();
19450   if (!VT.isVector())
19451     return false; // Bail if we hit a non-vector.
19452
19453   assert(Root.getSimpleValueType().isVector() &&
19454          "Shuffles operate on vector types!");
19455   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19456          "Can only combine shuffles of the same vector register size.");
19457
19458   if (!isTargetShuffle(Op.getOpcode()))
19459     return false;
19460   SmallVector<int, 16> OpMask;
19461   bool IsUnary;
19462   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19463   // We only can combine unary shuffles which we can decode the mask for.
19464   if (!HaveMask || !IsUnary)
19465     return false;
19466
19467   assert(VT.getVectorNumElements() == OpMask.size() &&
19468          "Different mask size from vector size!");
19469   assert(((RootMask.size() > OpMask.size() &&
19470            RootMask.size() % OpMask.size() == 0) ||
19471           (OpMask.size() > RootMask.size() &&
19472            OpMask.size() % RootMask.size() == 0) ||
19473           OpMask.size() == RootMask.size()) &&
19474          "The smaller number of elements must divide the larger.");
19475   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19476   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19477   assert(((RootRatio == 1 && OpRatio == 1) ||
19478           (RootRatio == 1) != (OpRatio == 1)) &&
19479          "Must not have a ratio for both incoming and op masks!");
19480
19481   SmallVector<int, 16> Mask;
19482   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19483
19484   // Merge this shuffle operation's mask into our accumulated mask. Note that
19485   // this shuffle's mask will be the first applied to the input, followed by the
19486   // root mask to get us all the way to the root value arrangement. The reason
19487   // for this order is that we are recursing up the operation chain.
19488   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19489     int RootIdx = i / RootRatio;
19490     if (RootMask[RootIdx] < 0) {
19491       // This is a zero or undef lane, we're done.
19492       Mask.push_back(RootMask[RootIdx]);
19493       continue;
19494     }
19495
19496     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19497     int OpIdx = RootMaskedIdx / OpRatio;
19498     if (OpMask[OpIdx] < 0) {
19499       // The incoming lanes are zero or undef, it doesn't matter which ones we
19500       // are using.
19501       Mask.push_back(OpMask[OpIdx]);
19502       continue;
19503     }
19504
19505     // Ok, we have non-zero lanes, map them through.
19506     Mask.push_back(OpMask[OpIdx] * OpRatio +
19507                    RootMaskedIdx % OpRatio);
19508   }
19509
19510   // See if we can recurse into the operand to combine more things.
19511   switch (Op.getOpcode()) {
19512     case X86ISD::PSHUFB:
19513       HasPSHUFB = true;
19514     case X86ISD::PSHUFD:
19515     case X86ISD::PSHUFHW:
19516     case X86ISD::PSHUFLW:
19517       if (Op.getOperand(0).hasOneUse() &&
19518           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19519                                         HasPSHUFB, DAG, DCI, Subtarget))
19520         return true;
19521       break;
19522
19523     case X86ISD::UNPCKL:
19524     case X86ISD::UNPCKH:
19525       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19526       // We can't check for single use, we have to check that this shuffle is the only user.
19527       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19528           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19529                                         HasPSHUFB, DAG, DCI, Subtarget))
19530           return true;
19531       break;
19532   }
19533
19534   // Minor canonicalization of the accumulated shuffle mask to make it easier
19535   // to match below. All this does is detect masks with squential pairs of
19536   // elements, and shrink them to the half-width mask. It does this in a loop
19537   // so it will reduce the size of the mask to the minimal width mask which
19538   // performs an equivalent shuffle.
19539   SmallVector<int, 16> WidenedMask;
19540   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19541     Mask = std::move(WidenedMask);
19542     WidenedMask.clear();
19543   }
19544
19545   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19546                                 Subtarget);
19547 }
19548
19549 /// \brief Get the PSHUF-style mask from PSHUF node.
19550 ///
19551 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19552 /// PSHUF-style masks that can be reused with such instructions.
19553 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19554   MVT VT = N.getSimpleValueType();
19555   SmallVector<int, 4> Mask;
19556   bool IsUnary;
19557   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19558   (void)HaveMask;
19559   assert(HaveMask);
19560
19561   // If we have more than 128-bits, only the low 128-bits of shuffle mask
19562   // matter. Check that the upper masks are repeats and remove them.
19563   if (VT.getSizeInBits() > 128) {
19564     int LaneElts = 128 / VT.getScalarSizeInBits();
19565 #ifndef NDEBUG
19566     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19567       for (int j = 0; j < LaneElts; ++j)
19568         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19569                "Mask doesn't repeat in high 128-bit lanes!");
19570 #endif
19571     Mask.resize(LaneElts);
19572   }
19573
19574   switch (N.getOpcode()) {
19575   case X86ISD::PSHUFD:
19576     return Mask;
19577   case X86ISD::PSHUFLW:
19578     Mask.resize(4);
19579     return Mask;
19580   case X86ISD::PSHUFHW:
19581     Mask.erase(Mask.begin(), Mask.begin() + 4);
19582     for (int &M : Mask)
19583       M -= 4;
19584     return Mask;
19585   default:
19586     llvm_unreachable("No valid shuffle instruction found!");
19587   }
19588 }
19589
19590 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19591 ///
19592 /// We walk up the chain and look for a combinable shuffle, skipping over
19593 /// shuffles that we could hoist this shuffle's transformation past without
19594 /// altering anything.
19595 static SDValue
19596 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19597                              SelectionDAG &DAG,
19598                              TargetLowering::DAGCombinerInfo &DCI) {
19599   assert(N.getOpcode() == X86ISD::PSHUFD &&
19600          "Called with something other than an x86 128-bit half shuffle!");
19601   SDLoc DL(N);
19602
19603   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19604   // of the shuffles in the chain so that we can form a fresh chain to replace
19605   // this one.
19606   SmallVector<SDValue, 8> Chain;
19607   SDValue V = N.getOperand(0);
19608   for (; V.hasOneUse(); V = V.getOperand(0)) {
19609     switch (V.getOpcode()) {
19610     default:
19611       return SDValue(); // Nothing combined!
19612
19613     case ISD::BITCAST:
19614       // Skip bitcasts as we always know the type for the target specific
19615       // instructions.
19616       continue;
19617
19618     case X86ISD::PSHUFD:
19619       // Found another dword shuffle.
19620       break;
19621
19622     case X86ISD::PSHUFLW:
19623       // Check that the low words (being shuffled) are the identity in the
19624       // dword shuffle, and the high words are self-contained.
19625       if (Mask[0] != 0 || Mask[1] != 1 ||
19626           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19627         return SDValue();
19628
19629       Chain.push_back(V);
19630       continue;
19631
19632     case X86ISD::PSHUFHW:
19633       // Check that the high words (being shuffled) are the identity in the
19634       // dword shuffle, and the low words are self-contained.
19635       if (Mask[2] != 2 || Mask[3] != 3 ||
19636           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19637         return SDValue();
19638
19639       Chain.push_back(V);
19640       continue;
19641
19642     case X86ISD::UNPCKL:
19643     case X86ISD::UNPCKH:
19644       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19645       // shuffle into a preceding word shuffle.
19646       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19647           V.getSimpleValueType().getScalarType() != MVT::i16)
19648         return SDValue();
19649
19650       // Search for a half-shuffle which we can combine with.
19651       unsigned CombineOp =
19652           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19653       if (V.getOperand(0) != V.getOperand(1) ||
19654           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19655         return SDValue();
19656       Chain.push_back(V);
19657       V = V.getOperand(0);
19658       do {
19659         switch (V.getOpcode()) {
19660         default:
19661           return SDValue(); // Nothing to combine.
19662
19663         case X86ISD::PSHUFLW:
19664         case X86ISD::PSHUFHW:
19665           if (V.getOpcode() == CombineOp)
19666             break;
19667
19668           Chain.push_back(V);
19669
19670           // Fallthrough!
19671         case ISD::BITCAST:
19672           V = V.getOperand(0);
19673           continue;
19674         }
19675         break;
19676       } while (V.hasOneUse());
19677       break;
19678     }
19679     // Break out of the loop if we break out of the switch.
19680     break;
19681   }
19682
19683   if (!V.hasOneUse())
19684     // We fell out of the loop without finding a viable combining instruction.
19685     return SDValue();
19686
19687   // Merge this node's mask and our incoming mask.
19688   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19689   for (int &M : Mask)
19690     M = VMask[M];
19691   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19692                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19693
19694   // Rebuild the chain around this new shuffle.
19695   while (!Chain.empty()) {
19696     SDValue W = Chain.pop_back_val();
19697
19698     if (V.getValueType() != W.getOperand(0).getValueType())
19699       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19700
19701     switch (W.getOpcode()) {
19702     default:
19703       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19704
19705     case X86ISD::UNPCKL:
19706     case X86ISD::UNPCKH:
19707       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19708       break;
19709
19710     case X86ISD::PSHUFD:
19711     case X86ISD::PSHUFLW:
19712     case X86ISD::PSHUFHW:
19713       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19714       break;
19715     }
19716   }
19717   if (V.getValueType() != N.getValueType())
19718     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19719
19720   // Return the new chain to replace N.
19721   return V;
19722 }
19723
19724 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19725 ///
19726 /// We walk up the chain, skipping shuffles of the other half and looking
19727 /// through shuffles which switch halves trying to find a shuffle of the same
19728 /// pair of dwords.
19729 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19730                                         SelectionDAG &DAG,
19731                                         TargetLowering::DAGCombinerInfo &DCI) {
19732   assert(
19733       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19734       "Called with something other than an x86 128-bit half shuffle!");
19735   SDLoc DL(N);
19736   unsigned CombineOpcode = N.getOpcode();
19737
19738   // Walk up a single-use chain looking for a combinable shuffle.
19739   SDValue V = N.getOperand(0);
19740   for (; V.hasOneUse(); V = V.getOperand(0)) {
19741     switch (V.getOpcode()) {
19742     default:
19743       return false; // Nothing combined!
19744
19745     case ISD::BITCAST:
19746       // Skip bitcasts as we always know the type for the target specific
19747       // instructions.
19748       continue;
19749
19750     case X86ISD::PSHUFLW:
19751     case X86ISD::PSHUFHW:
19752       if (V.getOpcode() == CombineOpcode)
19753         break;
19754
19755       // Other-half shuffles are no-ops.
19756       continue;
19757     }
19758     // Break out of the loop if we break out of the switch.
19759     break;
19760   }
19761
19762   if (!V.hasOneUse())
19763     // We fell out of the loop without finding a viable combining instruction.
19764     return false;
19765
19766   // Combine away the bottom node as its shuffle will be accumulated into
19767   // a preceding shuffle.
19768   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19769
19770   // Record the old value.
19771   SDValue Old = V;
19772
19773   // Merge this node's mask and our incoming mask (adjusted to account for all
19774   // the pshufd instructions encountered).
19775   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19776   for (int &M : Mask)
19777     M = VMask[M];
19778   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19779                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19780
19781   // Check that the shuffles didn't cancel each other out. If not, we need to
19782   // combine to the new one.
19783   if (Old != V)
19784     // Replace the combinable shuffle with the combined one, updating all users
19785     // so that we re-evaluate the chain here.
19786     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19787
19788   return true;
19789 }
19790
19791 /// \brief Try to combine x86 target specific shuffles.
19792 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19793                                            TargetLowering::DAGCombinerInfo &DCI,
19794                                            const X86Subtarget *Subtarget) {
19795   SDLoc DL(N);
19796   MVT VT = N.getSimpleValueType();
19797   SmallVector<int, 4> Mask;
19798
19799   switch (N.getOpcode()) {
19800   case X86ISD::PSHUFD:
19801   case X86ISD::PSHUFLW:
19802   case X86ISD::PSHUFHW:
19803     Mask = getPSHUFShuffleMask(N);
19804     assert(Mask.size() == 4);
19805     break;
19806   default:
19807     return SDValue();
19808   }
19809
19810   // Nuke no-op shuffles that show up after combining.
19811   if (isNoopShuffleMask(Mask))
19812     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19813
19814   // Look for simplifications involving one or two shuffle instructions.
19815   SDValue V = N.getOperand(0);
19816   switch (N.getOpcode()) {
19817   default:
19818     break;
19819   case X86ISD::PSHUFLW:
19820   case X86ISD::PSHUFHW:
19821     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
19822
19823     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19824       return SDValue(); // We combined away this shuffle, so we're done.
19825
19826     // See if this reduces to a PSHUFD which is no more expensive and can
19827     // combine with more operations. Note that it has to at least flip the
19828     // dwords as otherwise it would have been removed as a no-op.
19829     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
19830       int DMask[] = {0, 1, 2, 3};
19831       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19832       DMask[DOffset + 0] = DOffset + 1;
19833       DMask[DOffset + 1] = DOffset + 0;
19834       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
19835       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
19836       DCI.AddToWorklist(V.getNode());
19837       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
19838                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19839       DCI.AddToWorklist(V.getNode());
19840       return DAG.getNode(ISD::BITCAST, DL, VT, V);
19841     }
19842
19843     // Look for shuffle patterns which can be implemented as a single unpack.
19844     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19845     // only works when we have a PSHUFD followed by two half-shuffles.
19846     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19847         (V.getOpcode() == X86ISD::PSHUFLW ||
19848          V.getOpcode() == X86ISD::PSHUFHW) &&
19849         V.getOpcode() != N.getOpcode() &&
19850         V.hasOneUse()) {
19851       SDValue D = V.getOperand(0);
19852       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19853         D = D.getOperand(0);
19854       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19855         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19856         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19857         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19858         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19859         int WordMask[8];
19860         for (int i = 0; i < 4; ++i) {
19861           WordMask[i + NOffset] = Mask[i] + NOffset;
19862           WordMask[i + VOffset] = VMask[i] + VOffset;
19863         }
19864         // Map the word mask through the DWord mask.
19865         int MappedMask[8];
19866         for (int i = 0; i < 8; ++i)
19867           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19868         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19869             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
19870           // We can replace all three shuffles with an unpack.
19871           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
19872           DCI.AddToWorklist(V.getNode());
19873           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19874                                                 : X86ISD::UNPCKH,
19875                              DL, VT, V, V);
19876         }
19877       }
19878     }
19879
19880     break;
19881
19882   case X86ISD::PSHUFD:
19883     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19884       return NewN;
19885
19886     break;
19887   }
19888
19889   return SDValue();
19890 }
19891
19892 /// \brief Try to combine a shuffle into a target-specific add-sub node.
19893 ///
19894 /// We combine this directly on the abstract vector shuffle nodes so it is
19895 /// easier to generically match. We also insert dummy vector shuffle nodes for
19896 /// the operands which explicitly discard the lanes which are unused by this
19897 /// operation to try to flow through the rest of the combiner the fact that
19898 /// they're unused.
19899 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
19900   SDLoc DL(N);
19901   EVT VT = N->getValueType(0);
19902
19903   // We only handle target-independent shuffles.
19904   // FIXME: It would be easy and harmless to use the target shuffle mask
19905   // extraction tool to support more.
19906   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
19907     return SDValue();
19908
19909   auto *SVN = cast<ShuffleVectorSDNode>(N);
19910   ArrayRef<int> Mask = SVN->getMask();
19911   SDValue V1 = N->getOperand(0);
19912   SDValue V2 = N->getOperand(1);
19913
19914   // We require the first shuffle operand to be the SUB node, and the second to
19915   // be the ADD node.
19916   // FIXME: We should support the commuted patterns.
19917   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
19918     return SDValue();
19919
19920   // If there are other uses of these operations we can't fold them.
19921   if (!V1->hasOneUse() || !V2->hasOneUse())
19922     return SDValue();
19923
19924   // Ensure that both operations have the same operands. Note that we can
19925   // commute the FADD operands.
19926   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
19927   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
19928       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
19929     return SDValue();
19930
19931   // We're looking for blends between FADD and FSUB nodes. We insist on these
19932   // nodes being lined up in a specific expected pattern.
19933   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
19934         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
19935         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
19936     return SDValue();
19937
19938   // Only specific types are legal at this point, assert so we notice if and
19939   // when these change.
19940   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
19941           VT == MVT::v4f64) &&
19942          "Unknown vector type encountered!");
19943
19944   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
19945 }
19946
19947 /// PerformShuffleCombine - Performs several different shuffle combines.
19948 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19949                                      TargetLowering::DAGCombinerInfo &DCI,
19950                                      const X86Subtarget *Subtarget) {
19951   SDLoc dl(N);
19952   SDValue N0 = N->getOperand(0);
19953   SDValue N1 = N->getOperand(1);
19954   EVT VT = N->getValueType(0);
19955
19956   // Don't create instructions with illegal types after legalize types has run.
19957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19958   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19959     return SDValue();
19960
19961   // If we have legalized the vector types, look for blends of FADD and FSUB
19962   // nodes that we can fuse into an ADDSUB node.
19963   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
19964     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
19965       return AddSub;
19966
19967   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19968   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19969       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19970     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19971
19972   // During Type Legalization, when promoting illegal vector types,
19973   // the backend might introduce new shuffle dag nodes and bitcasts.
19974   //
19975   // This code performs the following transformation:
19976   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19977   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19978   //
19979   // We do this only if both the bitcast and the BINOP dag nodes have
19980   // one use. Also, perform this transformation only if the new binary
19981   // operation is legal. This is to avoid introducing dag nodes that
19982   // potentially need to be further expanded (or custom lowered) into a
19983   // less optimal sequence of dag nodes.
19984   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19985       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19986       N0.getOpcode() == ISD::BITCAST) {
19987     SDValue BC0 = N0.getOperand(0);
19988     EVT SVT = BC0.getValueType();
19989     unsigned Opcode = BC0.getOpcode();
19990     unsigned NumElts = VT.getVectorNumElements();
19991
19992     if (BC0.hasOneUse() && SVT.isVector() &&
19993         SVT.getVectorNumElements() * 2 == NumElts &&
19994         TLI.isOperationLegal(Opcode, VT)) {
19995       bool CanFold = false;
19996       switch (Opcode) {
19997       default : break;
19998       case ISD::ADD :
19999       case ISD::FADD :
20000       case ISD::SUB :
20001       case ISD::FSUB :
20002       case ISD::MUL :
20003       case ISD::FMUL :
20004         CanFold = true;
20005       }
20006
20007       unsigned SVTNumElts = SVT.getVectorNumElements();
20008       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20009       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20010         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20011       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20012         CanFold = SVOp->getMaskElt(i) < 0;
20013
20014       if (CanFold) {
20015         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20016         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20017         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20018         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20019       }
20020     }
20021   }
20022
20023   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20024   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20025   // consecutive, non-overlapping, and in the right order.
20026   SmallVector<SDValue, 16> Elts;
20027   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20028     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20029
20030   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20031   if (LD.getNode())
20032     return LD;
20033
20034   if (isTargetShuffle(N->getOpcode())) {
20035     SDValue Shuffle =
20036         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20037     if (Shuffle.getNode())
20038       return Shuffle;
20039
20040     // Try recursively combining arbitrary sequences of x86 shuffle
20041     // instructions into higher-order shuffles. We do this after combining
20042     // specific PSHUF instruction sequences into their minimal form so that we
20043     // can evaluate how many specialized shuffle instructions are involved in
20044     // a particular chain.
20045     SmallVector<int, 1> NonceMask; // Just a placeholder.
20046     NonceMask.push_back(0);
20047     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20048                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20049                                       DCI, Subtarget))
20050       return SDValue(); // This routine will use CombineTo to replace N.
20051   }
20052
20053   return SDValue();
20054 }
20055
20056 /// PerformTruncateCombine - Converts truncate operation to
20057 /// a sequence of vector shuffle operations.
20058 /// It is possible when we truncate 256-bit vector to 128-bit vector
20059 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20060                                       TargetLowering::DAGCombinerInfo &DCI,
20061                                       const X86Subtarget *Subtarget)  {
20062   return SDValue();
20063 }
20064
20065 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20066 /// specific shuffle of a load can be folded into a single element load.
20067 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20068 /// shuffles have been custom lowered so we need to handle those here.
20069 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20070                                          TargetLowering::DAGCombinerInfo &DCI) {
20071   if (DCI.isBeforeLegalizeOps())
20072     return SDValue();
20073
20074   SDValue InVec = N->getOperand(0);
20075   SDValue EltNo = N->getOperand(1);
20076
20077   if (!isa<ConstantSDNode>(EltNo))
20078     return SDValue();
20079
20080   EVT OriginalVT = InVec.getValueType();
20081
20082   if (InVec.getOpcode() == ISD::BITCAST) {
20083     // Don't duplicate a load with other uses.
20084     if (!InVec.hasOneUse())
20085       return SDValue();
20086     EVT BCVT = InVec.getOperand(0).getValueType();
20087     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20088       return SDValue();
20089     InVec = InVec.getOperand(0);
20090   }
20091
20092   EVT CurrentVT = InVec.getValueType();
20093
20094   if (!isTargetShuffle(InVec.getOpcode()))
20095     return SDValue();
20096
20097   // Don't duplicate a load with other uses.
20098   if (!InVec.hasOneUse())
20099     return SDValue();
20100
20101   SmallVector<int, 16> ShuffleMask;
20102   bool UnaryShuffle;
20103   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20104                             ShuffleMask, UnaryShuffle))
20105     return SDValue();
20106
20107   // Select the input vector, guarding against out of range extract vector.
20108   unsigned NumElems = CurrentVT.getVectorNumElements();
20109   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20110   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20111   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20112                                          : InVec.getOperand(1);
20113
20114   // If inputs to shuffle are the same for both ops, then allow 2 uses
20115   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20116                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20117
20118   if (LdNode.getOpcode() == ISD::BITCAST) {
20119     // Don't duplicate a load with other uses.
20120     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20121       return SDValue();
20122
20123     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20124     LdNode = LdNode.getOperand(0);
20125   }
20126
20127   if (!ISD::isNormalLoad(LdNode.getNode()))
20128     return SDValue();
20129
20130   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20131
20132   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20133     return SDValue();
20134
20135   EVT EltVT = N->getValueType(0);
20136   // If there's a bitcast before the shuffle, check if the load type and
20137   // alignment is valid.
20138   unsigned Align = LN0->getAlignment();
20139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20140   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20141       EltVT.getTypeForEVT(*DAG.getContext()));
20142
20143   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20144     return SDValue();
20145
20146   // All checks match so transform back to vector_shuffle so that DAG combiner
20147   // can finish the job
20148   SDLoc dl(N);
20149
20150   // Create shuffle node taking into account the case that its a unary shuffle
20151   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20152                                    : InVec.getOperand(1);
20153   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20154                                  InVec.getOperand(0), Shuffle,
20155                                  &ShuffleMask[0]);
20156   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20157   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20158                      EltNo);
20159 }
20160
20161 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20162 /// special and don't usually play with other vector types, it's better to
20163 /// handle them early to be sure we emit efficient code by avoiding
20164 /// store-load conversions.
20165 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20166   if (N->getValueType(0) != MVT::x86mmx ||
20167       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20168       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20169     return SDValue();
20170
20171   SDValue V = N->getOperand(0);
20172   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20173   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20174     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20175                        N->getValueType(0), V.getOperand(0));
20176
20177   return SDValue();
20178 }
20179
20180 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20181 /// generation and convert it from being a bunch of shuffles and extracts
20182 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20183 /// storing the value and loading scalars back, while for x64 we should
20184 /// use 64-bit extracts and shifts.
20185 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20186                                          TargetLowering::DAGCombinerInfo &DCI) {
20187   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20188   if (NewOp.getNode())
20189     return NewOp;
20190
20191   SDValue InputVector = N->getOperand(0);
20192
20193   // Detect mmx to i32 conversion through a v2i32 elt extract.
20194   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20195       N->getValueType(0) == MVT::i32 &&
20196       InputVector.getValueType() == MVT::v2i32) {
20197
20198     // The bitcast source is a direct mmx result.
20199     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20200     if (MMXSrc.getValueType() == MVT::x86mmx)
20201       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20202                          N->getValueType(0),
20203                          InputVector.getNode()->getOperand(0));
20204
20205     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20206     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20207     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20208         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20209         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20210         MMXSrcOp.getValueType() == MVT::v1i64 &&
20211         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20212       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20213                          N->getValueType(0),
20214                          MMXSrcOp.getOperand(0));
20215   }
20216
20217   // Only operate on vectors of 4 elements, where the alternative shuffling
20218   // gets to be more expensive.
20219   if (InputVector.getValueType() != MVT::v4i32)
20220     return SDValue();
20221
20222   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20223   // single use which is a sign-extend or zero-extend, and all elements are
20224   // used.
20225   SmallVector<SDNode *, 4> Uses;
20226   unsigned ExtractedElements = 0;
20227   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20228        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20229     if (UI.getUse().getResNo() != InputVector.getResNo())
20230       return SDValue();
20231
20232     SDNode *Extract = *UI;
20233     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20234       return SDValue();
20235
20236     if (Extract->getValueType(0) != MVT::i32)
20237       return SDValue();
20238     if (!Extract->hasOneUse())
20239       return SDValue();
20240     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20241         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20242       return SDValue();
20243     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20244       return SDValue();
20245
20246     // Record which element was extracted.
20247     ExtractedElements |=
20248       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20249
20250     Uses.push_back(Extract);
20251   }
20252
20253   // If not all the elements were used, this may not be worthwhile.
20254   if (ExtractedElements != 15)
20255     return SDValue();
20256
20257   // Ok, we've now decided to do the transformation.
20258   // If 64-bit shifts are legal, use the extract-shift sequence,
20259   // otherwise bounce the vector off the cache.
20260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20261   SDValue Vals[4];
20262   SDLoc dl(InputVector);
20263
20264   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20265     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20266     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20267     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20268       DAG.getConstant(0, VecIdxTy));
20269     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20270       DAG.getConstant(1, VecIdxTy));
20271
20272     SDValue ShAmt = DAG.getConstant(32,
20273       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20274     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20275     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20276       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20277     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20278     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20279       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20280   } else {
20281     // Store the value to a temporary stack slot.
20282     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20283     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20284       MachinePointerInfo(), false, false, 0);
20285
20286     EVT ElementType = InputVector.getValueType().getVectorElementType();
20287     unsigned EltSize = ElementType.getSizeInBits() / 8;
20288
20289     // Replace each use (extract) with a load of the appropriate element.
20290     for (unsigned i = 0; i < 4; ++i) {
20291       uint64_t Offset = EltSize * i;
20292       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20293
20294       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20295                                        StackPtr, OffsetVal);
20296
20297       // Load the scalar.
20298       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20299                             ScalarAddr, MachinePointerInfo(),
20300                             false, false, false, 0);
20301
20302     }
20303   }
20304
20305   // Replace the extracts
20306   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20307     UE = Uses.end(); UI != UE; ++UI) {
20308     SDNode *Extract = *UI;
20309
20310     SDValue Idx = Extract->getOperand(1);
20311     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20312     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20313   }
20314
20315   // The replacement was made in place; don't return anything.
20316   return SDValue();
20317 }
20318
20319 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20320 static std::pair<unsigned, bool>
20321 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20322                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20323   if (!VT.isVector())
20324     return std::make_pair(0, false);
20325
20326   bool NeedSplit = false;
20327   switch (VT.getSimpleVT().SimpleTy) {
20328   default: return std::make_pair(0, false);
20329   case MVT::v4i64:
20330   case MVT::v2i64:
20331     if (!Subtarget->hasVLX())
20332       return std::make_pair(0, false);
20333     break;
20334   case MVT::v64i8:
20335   case MVT::v32i16:
20336     if (!Subtarget->hasBWI())
20337       return std::make_pair(0, false);
20338     break;
20339   case MVT::v16i32:
20340   case MVT::v8i64:
20341     if (!Subtarget->hasAVX512())
20342       return std::make_pair(0, false);
20343     break;
20344   case MVT::v32i8:
20345   case MVT::v16i16:
20346   case MVT::v8i32:
20347     if (!Subtarget->hasAVX2())
20348       NeedSplit = true;
20349     if (!Subtarget->hasAVX())
20350       return std::make_pair(0, false);
20351     break;
20352   case MVT::v16i8:
20353   case MVT::v8i16:
20354   case MVT::v4i32:
20355     if (!Subtarget->hasSSE2())
20356       return std::make_pair(0, false);
20357   }
20358
20359   // SSE2 has only a small subset of the operations.
20360   bool hasUnsigned = Subtarget->hasSSE41() ||
20361                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20362   bool hasSigned = Subtarget->hasSSE41() ||
20363                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20364
20365   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20366
20367   unsigned Opc = 0;
20368   // Check for x CC y ? x : y.
20369   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20370       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20371     switch (CC) {
20372     default: break;
20373     case ISD::SETULT:
20374     case ISD::SETULE:
20375       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20376     case ISD::SETUGT:
20377     case ISD::SETUGE:
20378       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20379     case ISD::SETLT:
20380     case ISD::SETLE:
20381       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20382     case ISD::SETGT:
20383     case ISD::SETGE:
20384       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20385     }
20386   // Check for x CC y ? y : x -- a min/max with reversed arms.
20387   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20388              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20389     switch (CC) {
20390     default: break;
20391     case ISD::SETULT:
20392     case ISD::SETULE:
20393       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20394     case ISD::SETUGT:
20395     case ISD::SETUGE:
20396       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20397     case ISD::SETLT:
20398     case ISD::SETLE:
20399       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20400     case ISD::SETGT:
20401     case ISD::SETGE:
20402       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20403     }
20404   }
20405
20406   return std::make_pair(Opc, NeedSplit);
20407 }
20408
20409 static SDValue
20410 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20411                                       const X86Subtarget *Subtarget) {
20412   SDLoc dl(N);
20413   SDValue Cond = N->getOperand(0);
20414   SDValue LHS = N->getOperand(1);
20415   SDValue RHS = N->getOperand(2);
20416
20417   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20418     SDValue CondSrc = Cond->getOperand(0);
20419     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20420       Cond = CondSrc->getOperand(0);
20421   }
20422
20423   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20424     return SDValue();
20425
20426   // A vselect where all conditions and data are constants can be optimized into
20427   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20428   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20429       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20430     return SDValue();
20431
20432   unsigned MaskValue = 0;
20433   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20434     return SDValue();
20435
20436   MVT VT = N->getSimpleValueType(0);
20437   unsigned NumElems = VT.getVectorNumElements();
20438   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20439   for (unsigned i = 0; i < NumElems; ++i) {
20440     // Be sure we emit undef where we can.
20441     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20442       ShuffleMask[i] = -1;
20443     else
20444       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20445   }
20446
20447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20448   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20449     return SDValue();
20450   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20451 }
20452
20453 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20454 /// nodes.
20455 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20456                                     TargetLowering::DAGCombinerInfo &DCI,
20457                                     const X86Subtarget *Subtarget) {
20458   SDLoc DL(N);
20459   SDValue Cond = N->getOperand(0);
20460   // Get the LHS/RHS of the select.
20461   SDValue LHS = N->getOperand(1);
20462   SDValue RHS = N->getOperand(2);
20463   EVT VT = LHS.getValueType();
20464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20465
20466   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20467   // instructions match the semantics of the common C idiom x<y?x:y but not
20468   // x<=y?x:y, because of how they handle negative zero (which can be
20469   // ignored in unsafe-math mode).
20470   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20471   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20472       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20473       (Subtarget->hasSSE2() ||
20474        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20475     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20476
20477     unsigned Opcode = 0;
20478     // Check for x CC y ? x : y.
20479     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20480         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20481       switch (CC) {
20482       default: break;
20483       case ISD::SETULT:
20484         // Converting this to a min would handle NaNs incorrectly, and swapping
20485         // the operands would cause it to handle comparisons between positive
20486         // and negative zero incorrectly.
20487         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20488           if (!DAG.getTarget().Options.UnsafeFPMath &&
20489               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20490             break;
20491           std::swap(LHS, RHS);
20492         }
20493         Opcode = X86ISD::FMIN;
20494         break;
20495       case ISD::SETOLE:
20496         // Converting this to a min would handle comparisons between positive
20497         // and negative zero incorrectly.
20498         if (!DAG.getTarget().Options.UnsafeFPMath &&
20499             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20500           break;
20501         Opcode = X86ISD::FMIN;
20502         break;
20503       case ISD::SETULE:
20504         // Converting this to a min would handle both negative zeros and NaNs
20505         // incorrectly, but we can swap the operands to fix both.
20506         std::swap(LHS, RHS);
20507       case ISD::SETOLT:
20508       case ISD::SETLT:
20509       case ISD::SETLE:
20510         Opcode = X86ISD::FMIN;
20511         break;
20512
20513       case ISD::SETOGE:
20514         // Converting this to a max would handle comparisons between positive
20515         // and negative zero incorrectly.
20516         if (!DAG.getTarget().Options.UnsafeFPMath &&
20517             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20518           break;
20519         Opcode = X86ISD::FMAX;
20520         break;
20521       case ISD::SETUGT:
20522         // Converting this to a max would handle NaNs incorrectly, and swapping
20523         // the operands would cause it to handle comparisons between positive
20524         // and negative zero incorrectly.
20525         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20526           if (!DAG.getTarget().Options.UnsafeFPMath &&
20527               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20528             break;
20529           std::swap(LHS, RHS);
20530         }
20531         Opcode = X86ISD::FMAX;
20532         break;
20533       case ISD::SETUGE:
20534         // Converting this to a max would handle both negative zeros and NaNs
20535         // incorrectly, but we can swap the operands to fix both.
20536         std::swap(LHS, RHS);
20537       case ISD::SETOGT:
20538       case ISD::SETGT:
20539       case ISD::SETGE:
20540         Opcode = X86ISD::FMAX;
20541         break;
20542       }
20543     // Check for x CC y ? y : x -- a min/max with reversed arms.
20544     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20545                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20546       switch (CC) {
20547       default: break;
20548       case ISD::SETOGE:
20549         // Converting this to a min would handle comparisons between positive
20550         // and negative zero incorrectly, and swapping the operands would
20551         // cause it to handle NaNs incorrectly.
20552         if (!DAG.getTarget().Options.UnsafeFPMath &&
20553             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20554           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20555             break;
20556           std::swap(LHS, RHS);
20557         }
20558         Opcode = X86ISD::FMIN;
20559         break;
20560       case ISD::SETUGT:
20561         // Converting this to a min would handle NaNs incorrectly.
20562         if (!DAG.getTarget().Options.UnsafeFPMath &&
20563             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20564           break;
20565         Opcode = X86ISD::FMIN;
20566         break;
20567       case ISD::SETUGE:
20568         // Converting this to a min would handle both negative zeros and NaNs
20569         // incorrectly, but we can swap the operands to fix both.
20570         std::swap(LHS, RHS);
20571       case ISD::SETOGT:
20572       case ISD::SETGT:
20573       case ISD::SETGE:
20574         Opcode = X86ISD::FMIN;
20575         break;
20576
20577       case ISD::SETULT:
20578         // Converting this to a max would handle NaNs incorrectly.
20579         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20580           break;
20581         Opcode = X86ISD::FMAX;
20582         break;
20583       case ISD::SETOLE:
20584         // Converting this to a max would handle comparisons between positive
20585         // and negative zero incorrectly, and swapping the operands would
20586         // cause it to handle NaNs incorrectly.
20587         if (!DAG.getTarget().Options.UnsafeFPMath &&
20588             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20589           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20590             break;
20591           std::swap(LHS, RHS);
20592         }
20593         Opcode = X86ISD::FMAX;
20594         break;
20595       case ISD::SETULE:
20596         // Converting this to a max would handle both negative zeros and NaNs
20597         // incorrectly, but we can swap the operands to fix both.
20598         std::swap(LHS, RHS);
20599       case ISD::SETOLT:
20600       case ISD::SETLT:
20601       case ISD::SETLE:
20602         Opcode = X86ISD::FMAX;
20603         break;
20604       }
20605     }
20606
20607     if (Opcode)
20608       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20609   }
20610
20611   EVT CondVT = Cond.getValueType();
20612   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20613       CondVT.getVectorElementType() == MVT::i1) {
20614     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20615     // lowering on KNL. In this case we convert it to
20616     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20617     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20618     // Since SKX these selects have a proper lowering.
20619     EVT OpVT = LHS.getValueType();
20620     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20621         (OpVT.getVectorElementType() == MVT::i8 ||
20622          OpVT.getVectorElementType() == MVT::i16) &&
20623         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20624       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20625       DCI.AddToWorklist(Cond.getNode());
20626       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20627     }
20628   }
20629   // If this is a select between two integer constants, try to do some
20630   // optimizations.
20631   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20632     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20633       // Don't do this for crazy integer types.
20634       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20635         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20636         // so that TrueC (the true value) is larger than FalseC.
20637         bool NeedsCondInvert = false;
20638
20639         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20640             // Efficiently invertible.
20641             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20642              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20643               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20644           NeedsCondInvert = true;
20645           std::swap(TrueC, FalseC);
20646         }
20647
20648         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20649         if (FalseC->getAPIntValue() == 0 &&
20650             TrueC->getAPIntValue().isPowerOf2()) {
20651           if (NeedsCondInvert) // Invert the condition if needed.
20652             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20653                                DAG.getConstant(1, Cond.getValueType()));
20654
20655           // Zero extend the condition if needed.
20656           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20657
20658           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20659           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20660                              DAG.getConstant(ShAmt, MVT::i8));
20661         }
20662
20663         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20664         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20665           if (NeedsCondInvert) // Invert the condition if needed.
20666             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20667                                DAG.getConstant(1, Cond.getValueType()));
20668
20669           // Zero extend the condition if needed.
20670           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20671                              FalseC->getValueType(0), Cond);
20672           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20673                              SDValue(FalseC, 0));
20674         }
20675
20676         // Optimize cases that will turn into an LEA instruction.  This requires
20677         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20678         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20679           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20680           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20681
20682           bool isFastMultiplier = false;
20683           if (Diff < 10) {
20684             switch ((unsigned char)Diff) {
20685               default: break;
20686               case 1:  // result = add base, cond
20687               case 2:  // result = lea base(    , cond*2)
20688               case 3:  // result = lea base(cond, cond*2)
20689               case 4:  // result = lea base(    , cond*4)
20690               case 5:  // result = lea base(cond, cond*4)
20691               case 8:  // result = lea base(    , cond*8)
20692               case 9:  // result = lea base(cond, cond*8)
20693                 isFastMultiplier = true;
20694                 break;
20695             }
20696           }
20697
20698           if (isFastMultiplier) {
20699             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20700             if (NeedsCondInvert) // Invert the condition if needed.
20701               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20702                                  DAG.getConstant(1, Cond.getValueType()));
20703
20704             // Zero extend the condition if needed.
20705             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20706                                Cond);
20707             // Scale the condition by the difference.
20708             if (Diff != 1)
20709               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20710                                  DAG.getConstant(Diff, Cond.getValueType()));
20711
20712             // Add the base if non-zero.
20713             if (FalseC->getAPIntValue() != 0)
20714               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20715                                  SDValue(FalseC, 0));
20716             return Cond;
20717           }
20718         }
20719       }
20720   }
20721
20722   // Canonicalize max and min:
20723   // (x > y) ? x : y -> (x >= y) ? x : y
20724   // (x < y) ? x : y -> (x <= y) ? x : y
20725   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20726   // the need for an extra compare
20727   // against zero. e.g.
20728   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20729   // subl   %esi, %edi
20730   // testl  %edi, %edi
20731   // movl   $0, %eax
20732   // cmovgl %edi, %eax
20733   // =>
20734   // xorl   %eax, %eax
20735   // subl   %esi, $edi
20736   // cmovsl %eax, %edi
20737   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20738       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20739       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20740     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20741     switch (CC) {
20742     default: break;
20743     case ISD::SETLT:
20744     case ISD::SETGT: {
20745       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20746       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20747                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20748       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20749     }
20750     }
20751   }
20752
20753   // Early exit check
20754   if (!TLI.isTypeLegal(VT))
20755     return SDValue();
20756
20757   // Match VSELECTs into subs with unsigned saturation.
20758   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20759       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20760       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20761        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20762     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20763
20764     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20765     // left side invert the predicate to simplify logic below.
20766     SDValue Other;
20767     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20768       Other = RHS;
20769       CC = ISD::getSetCCInverse(CC, true);
20770     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20771       Other = LHS;
20772     }
20773
20774     if (Other.getNode() && Other->getNumOperands() == 2 &&
20775         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20776       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20777       SDValue CondRHS = Cond->getOperand(1);
20778
20779       // Look for a general sub with unsigned saturation first.
20780       // x >= y ? x-y : 0 --> subus x, y
20781       // x >  y ? x-y : 0 --> subus x, y
20782       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20783           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20784         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20785
20786       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20787         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20788           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20789             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20790               // If the RHS is a constant we have to reverse the const
20791               // canonicalization.
20792               // x > C-1 ? x+-C : 0 --> subus x, C
20793               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20794                   CondRHSConst->getAPIntValue() ==
20795                       (-OpRHSConst->getAPIntValue() - 1))
20796                 return DAG.getNode(
20797                     X86ISD::SUBUS, DL, VT, OpLHS,
20798                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20799
20800           // Another special case: If C was a sign bit, the sub has been
20801           // canonicalized into a xor.
20802           // FIXME: Would it be better to use computeKnownBits to determine
20803           //        whether it's safe to decanonicalize the xor?
20804           // x s< 0 ? x^C : 0 --> subus x, C
20805           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20806               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20807               OpRHSConst->getAPIntValue().isSignBit())
20808             // Note that we have to rebuild the RHS constant here to ensure we
20809             // don't rely on particular values of undef lanes.
20810             return DAG.getNode(
20811                 X86ISD::SUBUS, DL, VT, OpLHS,
20812                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20813         }
20814     }
20815   }
20816
20817   // Try to match a min/max vector operation.
20818   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20819     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20820     unsigned Opc = ret.first;
20821     bool NeedSplit = ret.second;
20822
20823     if (Opc && NeedSplit) {
20824       unsigned NumElems = VT.getVectorNumElements();
20825       // Extract the LHS vectors
20826       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20827       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20828
20829       // Extract the RHS vectors
20830       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20831       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20832
20833       // Create min/max for each subvector
20834       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20835       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20836
20837       // Merge the result
20838       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20839     } else if (Opc)
20840       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20841   }
20842
20843   // Simplify vector selection if condition value type matches vselect
20844   // operand type
20845   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
20846     assert(Cond.getValueType().isVector() &&
20847            "vector select expects a vector selector!");
20848
20849     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20850     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20851
20852     // Try invert the condition if true value is not all 1s and false value
20853     // is not all 0s.
20854     if (!TValIsAllOnes && !FValIsAllZeros &&
20855         // Check if the selector will be produced by CMPP*/PCMP*
20856         Cond.getOpcode() == ISD::SETCC &&
20857         // Check if SETCC has already been promoted
20858         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
20859       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20860       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20861
20862       if (TValIsAllZeros || FValIsAllOnes) {
20863         SDValue CC = Cond.getOperand(2);
20864         ISD::CondCode NewCC =
20865           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20866                                Cond.getOperand(0).getValueType().isInteger());
20867         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20868         std::swap(LHS, RHS);
20869         TValIsAllOnes = FValIsAllOnes;
20870         FValIsAllZeros = TValIsAllZeros;
20871       }
20872     }
20873
20874     if (TValIsAllOnes || FValIsAllZeros) {
20875       SDValue Ret;
20876
20877       if (TValIsAllOnes && FValIsAllZeros)
20878         Ret = Cond;
20879       else if (TValIsAllOnes)
20880         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20881                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20882       else if (FValIsAllZeros)
20883         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20884                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20885
20886       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20887     }
20888   }
20889
20890   // We should generate an X86ISD::BLENDI from a vselect if its argument
20891   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20892   // constants. This specific pattern gets generated when we split a
20893   // selector for a 512 bit vector in a machine without AVX512 (but with
20894   // 256-bit vectors), during legalization:
20895   //
20896   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20897   //
20898   // Iff we find this pattern and the build_vectors are built from
20899   // constants, we translate the vselect into a shuffle_vector that we
20900   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20901   if ((N->getOpcode() == ISD::VSELECT ||
20902        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
20903       !DCI.isBeforeLegalize()) {
20904     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20905     if (Shuffle.getNode())
20906       return Shuffle;
20907   }
20908
20909   // If this is a *dynamic* select (non-constant condition) and we can match
20910   // this node with one of the variable blend instructions, restructure the
20911   // condition so that the blends can use the high bit of each element and use
20912   // SimplifyDemandedBits to simplify the condition operand.
20913   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20914       !DCI.isBeforeLegalize() &&
20915       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
20916     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20917
20918     // Don't optimize vector selects that map to mask-registers.
20919     if (BitWidth == 1)
20920       return SDValue();
20921
20922     // We can only handle the cases where VSELECT is directly legal on the
20923     // subtarget. We custom lower VSELECT nodes with constant conditions and
20924     // this makes it hard to see whether a dynamic VSELECT will correctly
20925     // lower, so we both check the operation's status and explicitly handle the
20926     // cases where a *dynamic* blend will fail even though a constant-condition
20927     // blend could be custom lowered.
20928     // FIXME: We should find a better way to handle this class of problems.
20929     // Potentially, we should combine constant-condition vselect nodes
20930     // pre-legalization into shuffles and not mark as many types as custom
20931     // lowered.
20932     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
20933       return SDValue();
20934     // FIXME: We don't support i16-element blends currently. We could and
20935     // should support them by making *all* the bits in the condition be set
20936     // rather than just the high bit and using an i8-element blend.
20937     if (VT.getScalarType() == MVT::i16)
20938       return SDValue();
20939     // Dynamic blending was only available from SSE4.1 onward.
20940     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
20941       return SDValue();
20942     // Byte blends are only available in AVX2
20943     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
20944         !Subtarget->hasAVX2())
20945       return SDValue();
20946
20947     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20948     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20949
20950     APInt KnownZero, KnownOne;
20951     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20952                                           DCI.isBeforeLegalizeOps());
20953     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20954         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
20955                                  TLO)) {
20956       // If we changed the computation somewhere in the DAG, this change
20957       // will affect all users of Cond.
20958       // Make sure it is fine and update all the nodes so that we do not
20959       // use the generic VSELECT anymore. Otherwise, we may perform
20960       // wrong optimizations as we messed up with the actual expectation
20961       // for the vector boolean values.
20962       if (Cond != TLO.Old) {
20963         // Check all uses of that condition operand to check whether it will be
20964         // consumed by non-BLEND instructions, which may depend on all bits are
20965         // set properly.
20966         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20967              I != E; ++I)
20968           if (I->getOpcode() != ISD::VSELECT)
20969             // TODO: Add other opcodes eventually lowered into BLEND.
20970             return SDValue();
20971
20972         // Update all the users of the condition, before committing the change,
20973         // so that the VSELECT optimizations that expect the correct vector
20974         // boolean value will not be triggered.
20975         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20976              I != E; ++I)
20977           DAG.ReplaceAllUsesOfValueWith(
20978               SDValue(*I, 0),
20979               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
20980                           Cond, I->getOperand(1), I->getOperand(2)));
20981         DCI.CommitTargetLoweringOpt(TLO);
20982         return SDValue();
20983       }
20984       // At this point, only Cond is changed. Change the condition
20985       // just for N to keep the opportunity to optimize all other
20986       // users their own way.
20987       DAG.ReplaceAllUsesOfValueWith(
20988           SDValue(N, 0),
20989           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
20990                       TLO.New, N->getOperand(1), N->getOperand(2)));
20991       return SDValue();
20992     }
20993   }
20994
20995   return SDValue();
20996 }
20997
20998 // Check whether a boolean test is testing a boolean value generated by
20999 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21000 // code.
21001 //
21002 // Simplify the following patterns:
21003 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21004 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21005 // to (Op EFLAGS Cond)
21006 //
21007 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21008 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21009 // to (Op EFLAGS !Cond)
21010 //
21011 // where Op could be BRCOND or CMOV.
21012 //
21013 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21014   // Quit if not CMP and SUB with its value result used.
21015   if (Cmp.getOpcode() != X86ISD::CMP &&
21016       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21017       return SDValue();
21018
21019   // Quit if not used as a boolean value.
21020   if (CC != X86::COND_E && CC != X86::COND_NE)
21021     return SDValue();
21022
21023   // Check CMP operands. One of them should be 0 or 1 and the other should be
21024   // an SetCC or extended from it.
21025   SDValue Op1 = Cmp.getOperand(0);
21026   SDValue Op2 = Cmp.getOperand(1);
21027
21028   SDValue SetCC;
21029   const ConstantSDNode* C = nullptr;
21030   bool needOppositeCond = (CC == X86::COND_E);
21031   bool checkAgainstTrue = false; // Is it a comparison against 1?
21032
21033   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21034     SetCC = Op2;
21035   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21036     SetCC = Op1;
21037   else // Quit if all operands are not constants.
21038     return SDValue();
21039
21040   if (C->getZExtValue() == 1) {
21041     needOppositeCond = !needOppositeCond;
21042     checkAgainstTrue = true;
21043   } else if (C->getZExtValue() != 0)
21044     // Quit if the constant is neither 0 or 1.
21045     return SDValue();
21046
21047   bool truncatedToBoolWithAnd = false;
21048   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21049   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21050          SetCC.getOpcode() == ISD::TRUNCATE ||
21051          SetCC.getOpcode() == ISD::AND) {
21052     if (SetCC.getOpcode() == ISD::AND) {
21053       int OpIdx = -1;
21054       ConstantSDNode *CS;
21055       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21056           CS->getZExtValue() == 1)
21057         OpIdx = 1;
21058       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21059           CS->getZExtValue() == 1)
21060         OpIdx = 0;
21061       if (OpIdx == -1)
21062         break;
21063       SetCC = SetCC.getOperand(OpIdx);
21064       truncatedToBoolWithAnd = true;
21065     } else
21066       SetCC = SetCC.getOperand(0);
21067   }
21068
21069   switch (SetCC.getOpcode()) {
21070   case X86ISD::SETCC_CARRY:
21071     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21072     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21073     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21074     // truncated to i1 using 'and'.
21075     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21076       break;
21077     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21078            "Invalid use of SETCC_CARRY!");
21079     // FALL THROUGH
21080   case X86ISD::SETCC:
21081     // Set the condition code or opposite one if necessary.
21082     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21083     if (needOppositeCond)
21084       CC = X86::GetOppositeBranchCondition(CC);
21085     return SetCC.getOperand(1);
21086   case X86ISD::CMOV: {
21087     // Check whether false/true value has canonical one, i.e. 0 or 1.
21088     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21089     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21090     // Quit if true value is not a constant.
21091     if (!TVal)
21092       return SDValue();
21093     // Quit if false value is not a constant.
21094     if (!FVal) {
21095       SDValue Op = SetCC.getOperand(0);
21096       // Skip 'zext' or 'trunc' node.
21097       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21098           Op.getOpcode() == ISD::TRUNCATE)
21099         Op = Op.getOperand(0);
21100       // A special case for rdrand/rdseed, where 0 is set if false cond is
21101       // found.
21102       if ((Op.getOpcode() != X86ISD::RDRAND &&
21103            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21104         return SDValue();
21105     }
21106     // Quit if false value is not the constant 0 or 1.
21107     bool FValIsFalse = true;
21108     if (FVal && FVal->getZExtValue() != 0) {
21109       if (FVal->getZExtValue() != 1)
21110         return SDValue();
21111       // If FVal is 1, opposite cond is needed.
21112       needOppositeCond = !needOppositeCond;
21113       FValIsFalse = false;
21114     }
21115     // Quit if TVal is not the constant opposite of FVal.
21116     if (FValIsFalse && TVal->getZExtValue() != 1)
21117       return SDValue();
21118     if (!FValIsFalse && TVal->getZExtValue() != 0)
21119       return SDValue();
21120     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21121     if (needOppositeCond)
21122       CC = X86::GetOppositeBranchCondition(CC);
21123     return SetCC.getOperand(3);
21124   }
21125   }
21126
21127   return SDValue();
21128 }
21129
21130 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21131 /// Match:
21132 ///   (X86or (X86setcc) (X86setcc))
21133 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21134 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21135                                            X86::CondCode &CC1, SDValue &Flags,
21136                                            bool &isAnd) {
21137   if (Cond->getOpcode() == X86ISD::CMP) {
21138     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21139     if (!CondOp1C || !CondOp1C->isNullValue())
21140       return false;
21141
21142     Cond = Cond->getOperand(0);
21143   }
21144
21145   isAnd = false;
21146
21147   SDValue SetCC0, SetCC1;
21148   switch (Cond->getOpcode()) {
21149   default: return false;
21150   case ISD::AND:
21151   case X86ISD::AND:
21152     isAnd = true;
21153     // fallthru
21154   case ISD::OR:
21155   case X86ISD::OR:
21156     SetCC0 = Cond->getOperand(0);
21157     SetCC1 = Cond->getOperand(1);
21158     break;
21159   };
21160
21161   // Make sure we have SETCC nodes, using the same flags value.
21162   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21163       SetCC1.getOpcode() != X86ISD::SETCC ||
21164       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21165     return false;
21166
21167   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21168   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21169   Flags = SetCC0->getOperand(1);
21170   return true;
21171 }
21172
21173 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21174 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21175                                   TargetLowering::DAGCombinerInfo &DCI,
21176                                   const X86Subtarget *Subtarget) {
21177   SDLoc DL(N);
21178
21179   // If the flag operand isn't dead, don't touch this CMOV.
21180   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21181     return SDValue();
21182
21183   SDValue FalseOp = N->getOperand(0);
21184   SDValue TrueOp = N->getOperand(1);
21185   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21186   SDValue Cond = N->getOperand(3);
21187
21188   if (CC == X86::COND_E || CC == X86::COND_NE) {
21189     switch (Cond.getOpcode()) {
21190     default: break;
21191     case X86ISD::BSR:
21192     case X86ISD::BSF:
21193       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21194       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21195         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21196     }
21197   }
21198
21199   SDValue Flags;
21200
21201   Flags = checkBoolTestSetCCCombine(Cond, CC);
21202   if (Flags.getNode() &&
21203       // Extra check as FCMOV only supports a subset of X86 cond.
21204       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21205     SDValue Ops[] = { FalseOp, TrueOp,
21206                       DAG.getConstant(CC, MVT::i8), Flags };
21207     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21208   }
21209
21210   // If this is a select between two integer constants, try to do some
21211   // optimizations.  Note that the operands are ordered the opposite of SELECT
21212   // operands.
21213   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21214     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21215       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21216       // larger than FalseC (the false value).
21217       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21218         CC = X86::GetOppositeBranchCondition(CC);
21219         std::swap(TrueC, FalseC);
21220         std::swap(TrueOp, FalseOp);
21221       }
21222
21223       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21224       // This is efficient for any integer data type (including i8/i16) and
21225       // shift amount.
21226       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21227         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21228                            DAG.getConstant(CC, MVT::i8), Cond);
21229
21230         // Zero extend the condition if needed.
21231         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21232
21233         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21234         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21235                            DAG.getConstant(ShAmt, MVT::i8));
21236         if (N->getNumValues() == 2)  // Dead flag value?
21237           return DCI.CombineTo(N, Cond, SDValue());
21238         return Cond;
21239       }
21240
21241       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21242       // for any integer data type, including i8/i16.
21243       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21244         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21245                            DAG.getConstant(CC, MVT::i8), Cond);
21246
21247         // Zero extend the condition if needed.
21248         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21249                            FalseC->getValueType(0), Cond);
21250         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21251                            SDValue(FalseC, 0));
21252
21253         if (N->getNumValues() == 2)  // Dead flag value?
21254           return DCI.CombineTo(N, Cond, SDValue());
21255         return Cond;
21256       }
21257
21258       // Optimize cases that will turn into an LEA instruction.  This requires
21259       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21260       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21261         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21262         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21263
21264         bool isFastMultiplier = false;
21265         if (Diff < 10) {
21266           switch ((unsigned char)Diff) {
21267           default: break;
21268           case 1:  // result = add base, cond
21269           case 2:  // result = lea base(    , cond*2)
21270           case 3:  // result = lea base(cond, cond*2)
21271           case 4:  // result = lea base(    , cond*4)
21272           case 5:  // result = lea base(cond, cond*4)
21273           case 8:  // result = lea base(    , cond*8)
21274           case 9:  // result = lea base(cond, cond*8)
21275             isFastMultiplier = true;
21276             break;
21277           }
21278         }
21279
21280         if (isFastMultiplier) {
21281           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21282           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21283                              DAG.getConstant(CC, MVT::i8), Cond);
21284           // Zero extend the condition if needed.
21285           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21286                              Cond);
21287           // Scale the condition by the difference.
21288           if (Diff != 1)
21289             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21290                                DAG.getConstant(Diff, Cond.getValueType()));
21291
21292           // Add the base if non-zero.
21293           if (FalseC->getAPIntValue() != 0)
21294             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21295                                SDValue(FalseC, 0));
21296           if (N->getNumValues() == 2)  // Dead flag value?
21297             return DCI.CombineTo(N, Cond, SDValue());
21298           return Cond;
21299         }
21300       }
21301     }
21302   }
21303
21304   // Handle these cases:
21305   //   (select (x != c), e, c) -> select (x != c), e, x),
21306   //   (select (x == c), c, e) -> select (x == c), x, e)
21307   // where the c is an integer constant, and the "select" is the combination
21308   // of CMOV and CMP.
21309   //
21310   // The rationale for this change is that the conditional-move from a constant
21311   // needs two instructions, however, conditional-move from a register needs
21312   // only one instruction.
21313   //
21314   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21315   //  some instruction-combining opportunities. This opt needs to be
21316   //  postponed as late as possible.
21317   //
21318   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21319     // the DCI.xxxx conditions are provided to postpone the optimization as
21320     // late as possible.
21321
21322     ConstantSDNode *CmpAgainst = nullptr;
21323     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21324         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21325         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21326
21327       if (CC == X86::COND_NE &&
21328           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21329         CC = X86::GetOppositeBranchCondition(CC);
21330         std::swap(TrueOp, FalseOp);
21331       }
21332
21333       if (CC == X86::COND_E &&
21334           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21335         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21336                           DAG.getConstant(CC, MVT::i8), Cond };
21337         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21338       }
21339     }
21340   }
21341
21342   // Fold and/or of setcc's to double CMOV:
21343   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21344   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21345   //
21346   // This combine lets us generate:
21347   //   cmovcc1 (jcc1 if we don't have CMOV)
21348   //   cmovcc2 (same)
21349   // instead of:
21350   //   setcc1
21351   //   setcc2
21352   //   and/or
21353   //   cmovne (jne if we don't have CMOV)
21354   // When we can't use the CMOV instruction, it might increase branch
21355   // mispredicts.
21356   // When we can use CMOV, or when there is no mispredict, this improves
21357   // throughput and reduces register pressure.
21358   //
21359   if (CC == X86::COND_NE) {
21360     SDValue Flags;
21361     X86::CondCode CC0, CC1;
21362     bool isAndSetCC;
21363     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21364       if (isAndSetCC) {
21365         std::swap(FalseOp, TrueOp);
21366         CC0 = X86::GetOppositeBranchCondition(CC0);
21367         CC1 = X86::GetOppositeBranchCondition(CC1);
21368       }
21369
21370       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21371         Flags};
21372       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21373       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21374       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21375       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21376       return CMOV;
21377     }
21378   }
21379
21380   return SDValue();
21381 }
21382
21383 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21384                                                 const X86Subtarget *Subtarget) {
21385   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21386   switch (IntNo) {
21387   default: return SDValue();
21388   // SSE/AVX/AVX2 blend intrinsics.
21389   case Intrinsic::x86_avx2_pblendvb:
21390     // Don't try to simplify this intrinsic if we don't have AVX2.
21391     if (!Subtarget->hasAVX2())
21392       return SDValue();
21393     // FALL-THROUGH
21394   case Intrinsic::x86_avx_blendv_pd_256:
21395   case Intrinsic::x86_avx_blendv_ps_256:
21396     // Don't try to simplify this intrinsic if we don't have AVX.
21397     if (!Subtarget->hasAVX())
21398       return SDValue();
21399     // FALL-THROUGH
21400   case Intrinsic::x86_sse41_blendvps:
21401   case Intrinsic::x86_sse41_blendvpd:
21402   case Intrinsic::x86_sse41_pblendvb: {
21403     SDValue Op0 = N->getOperand(1);
21404     SDValue Op1 = N->getOperand(2);
21405     SDValue Mask = N->getOperand(3);
21406
21407     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21408     if (!Subtarget->hasSSE41())
21409       return SDValue();
21410
21411     // fold (blend A, A, Mask) -> A
21412     if (Op0 == Op1)
21413       return Op0;
21414     // fold (blend A, B, allZeros) -> A
21415     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21416       return Op0;
21417     // fold (blend A, B, allOnes) -> B
21418     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21419       return Op1;
21420
21421     // Simplify the case where the mask is a constant i32 value.
21422     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21423       if (C->isNullValue())
21424         return Op0;
21425       if (C->isAllOnesValue())
21426         return Op1;
21427     }
21428
21429     return SDValue();
21430   }
21431
21432   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21433   case Intrinsic::x86_sse2_psrai_w:
21434   case Intrinsic::x86_sse2_psrai_d:
21435   case Intrinsic::x86_avx2_psrai_w:
21436   case Intrinsic::x86_avx2_psrai_d:
21437   case Intrinsic::x86_sse2_psra_w:
21438   case Intrinsic::x86_sse2_psra_d:
21439   case Intrinsic::x86_avx2_psra_w:
21440   case Intrinsic::x86_avx2_psra_d: {
21441     SDValue Op0 = N->getOperand(1);
21442     SDValue Op1 = N->getOperand(2);
21443     EVT VT = Op0.getValueType();
21444     assert(VT.isVector() && "Expected a vector type!");
21445
21446     if (isa<BuildVectorSDNode>(Op1))
21447       Op1 = Op1.getOperand(0);
21448
21449     if (!isa<ConstantSDNode>(Op1))
21450       return SDValue();
21451
21452     EVT SVT = VT.getVectorElementType();
21453     unsigned SVTBits = SVT.getSizeInBits();
21454
21455     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21456     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21457     uint64_t ShAmt = C.getZExtValue();
21458
21459     // Don't try to convert this shift into a ISD::SRA if the shift
21460     // count is bigger than or equal to the element size.
21461     if (ShAmt >= SVTBits)
21462       return SDValue();
21463
21464     // Trivial case: if the shift count is zero, then fold this
21465     // into the first operand.
21466     if (ShAmt == 0)
21467       return Op0;
21468
21469     // Replace this packed shift intrinsic with a target independent
21470     // shift dag node.
21471     SDValue Splat = DAG.getConstant(C, VT);
21472     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21473   }
21474   }
21475 }
21476
21477 /// PerformMulCombine - Optimize a single multiply with constant into two
21478 /// in order to implement it with two cheaper instructions, e.g.
21479 /// LEA + SHL, LEA + LEA.
21480 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21481                                  TargetLowering::DAGCombinerInfo &DCI) {
21482   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21483     return SDValue();
21484
21485   EVT VT = N->getValueType(0);
21486   if (VT != MVT::i64 && VT != MVT::i32)
21487     return SDValue();
21488
21489   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21490   if (!C)
21491     return SDValue();
21492   uint64_t MulAmt = C->getZExtValue();
21493   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21494     return SDValue();
21495
21496   uint64_t MulAmt1 = 0;
21497   uint64_t MulAmt2 = 0;
21498   if ((MulAmt % 9) == 0) {
21499     MulAmt1 = 9;
21500     MulAmt2 = MulAmt / 9;
21501   } else if ((MulAmt % 5) == 0) {
21502     MulAmt1 = 5;
21503     MulAmt2 = MulAmt / 5;
21504   } else if ((MulAmt % 3) == 0) {
21505     MulAmt1 = 3;
21506     MulAmt2 = MulAmt / 3;
21507   }
21508   if (MulAmt2 &&
21509       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21510     SDLoc DL(N);
21511
21512     if (isPowerOf2_64(MulAmt2) &&
21513         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21514       // If second multiplifer is pow2, issue it first. We want the multiply by
21515       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21516       // is an add.
21517       std::swap(MulAmt1, MulAmt2);
21518
21519     SDValue NewMul;
21520     if (isPowerOf2_64(MulAmt1))
21521       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21522                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21523     else
21524       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21525                            DAG.getConstant(MulAmt1, VT));
21526
21527     if (isPowerOf2_64(MulAmt2))
21528       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21529                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21530     else
21531       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21532                            DAG.getConstant(MulAmt2, VT));
21533
21534     // Do not add new nodes to DAG combiner worklist.
21535     DCI.CombineTo(N, NewMul, false);
21536   }
21537   return SDValue();
21538 }
21539
21540 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21541   SDValue N0 = N->getOperand(0);
21542   SDValue N1 = N->getOperand(1);
21543   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21544   EVT VT = N0.getValueType();
21545
21546   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21547   // since the result of setcc_c is all zero's or all ones.
21548   if (VT.isInteger() && !VT.isVector() &&
21549       N1C && N0.getOpcode() == ISD::AND &&
21550       N0.getOperand(1).getOpcode() == ISD::Constant) {
21551     SDValue N00 = N0.getOperand(0);
21552     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21553         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21554           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21555          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21556       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21557       APInt ShAmt = N1C->getAPIntValue();
21558       Mask = Mask.shl(ShAmt);
21559       if (Mask != 0)
21560         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21561                            N00, DAG.getConstant(Mask, VT));
21562     }
21563   }
21564
21565   // Hardware support for vector shifts is sparse which makes us scalarize the
21566   // vector operations in many cases. Also, on sandybridge ADD is faster than
21567   // shl.
21568   // (shl V, 1) -> add V,V
21569   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21570     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21571       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21572       // We shift all of the values by one. In many cases we do not have
21573       // hardware support for this operation. This is better expressed as an ADD
21574       // of two values.
21575       if (N1SplatC->getZExtValue() == 1)
21576         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21577     }
21578
21579   return SDValue();
21580 }
21581
21582 /// \brief Returns a vector of 0s if the node in input is a vector logical
21583 /// shift by a constant amount which is known to be bigger than or equal
21584 /// to the vector element size in bits.
21585 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21586                                       const X86Subtarget *Subtarget) {
21587   EVT VT = N->getValueType(0);
21588
21589   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21590       (!Subtarget->hasInt256() ||
21591        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21592     return SDValue();
21593
21594   SDValue Amt = N->getOperand(1);
21595   SDLoc DL(N);
21596   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21597     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21598       APInt ShiftAmt = AmtSplat->getAPIntValue();
21599       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21600
21601       // SSE2/AVX2 logical shifts always return a vector of 0s
21602       // if the shift amount is bigger than or equal to
21603       // the element size. The constant shift amount will be
21604       // encoded as a 8-bit immediate.
21605       if (ShiftAmt.trunc(8).uge(MaxAmount))
21606         return getZeroVector(VT, Subtarget, DAG, DL);
21607     }
21608
21609   return SDValue();
21610 }
21611
21612 /// PerformShiftCombine - Combine shifts.
21613 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21614                                    TargetLowering::DAGCombinerInfo &DCI,
21615                                    const X86Subtarget *Subtarget) {
21616   if (N->getOpcode() == ISD::SHL) {
21617     SDValue V = PerformSHLCombine(N, DAG);
21618     if (V.getNode()) return V;
21619   }
21620
21621   if (N->getOpcode() != ISD::SRA) {
21622     // Try to fold this logical shift into a zero vector.
21623     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21624     if (V.getNode()) return V;
21625   }
21626
21627   return SDValue();
21628 }
21629
21630 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21631 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21632 // and friends.  Likewise for OR -> CMPNEQSS.
21633 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21634                             TargetLowering::DAGCombinerInfo &DCI,
21635                             const X86Subtarget *Subtarget) {
21636   unsigned opcode;
21637
21638   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21639   // we're requiring SSE2 for both.
21640   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21641     SDValue N0 = N->getOperand(0);
21642     SDValue N1 = N->getOperand(1);
21643     SDValue CMP0 = N0->getOperand(1);
21644     SDValue CMP1 = N1->getOperand(1);
21645     SDLoc DL(N);
21646
21647     // The SETCCs should both refer to the same CMP.
21648     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21649       return SDValue();
21650
21651     SDValue CMP00 = CMP0->getOperand(0);
21652     SDValue CMP01 = CMP0->getOperand(1);
21653     EVT     VT    = CMP00.getValueType();
21654
21655     if (VT == MVT::f32 || VT == MVT::f64) {
21656       bool ExpectingFlags = false;
21657       // Check for any users that want flags:
21658       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21659            !ExpectingFlags && UI != UE; ++UI)
21660         switch (UI->getOpcode()) {
21661         default:
21662         case ISD::BR_CC:
21663         case ISD::BRCOND:
21664         case ISD::SELECT:
21665           ExpectingFlags = true;
21666           break;
21667         case ISD::CopyToReg:
21668         case ISD::SIGN_EXTEND:
21669         case ISD::ZERO_EXTEND:
21670         case ISD::ANY_EXTEND:
21671           break;
21672         }
21673
21674       if (!ExpectingFlags) {
21675         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21676         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21677
21678         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21679           X86::CondCode tmp = cc0;
21680           cc0 = cc1;
21681           cc1 = tmp;
21682         }
21683
21684         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21685             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21686           // FIXME: need symbolic constants for these magic numbers.
21687           // See X86ATTInstPrinter.cpp:printSSECC().
21688           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21689           if (Subtarget->hasAVX512()) {
21690             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21691                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21692             if (N->getValueType(0) != MVT::i1)
21693               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21694                                  FSetCC);
21695             return FSetCC;
21696           }
21697           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21698                                               CMP00.getValueType(), CMP00, CMP01,
21699                                               DAG.getConstant(x86cc, MVT::i8));
21700
21701           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21702           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21703
21704           if (is64BitFP && !Subtarget->is64Bit()) {
21705             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21706             // 64-bit integer, since that's not a legal type. Since
21707             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21708             // bits, but can do this little dance to extract the lowest 32 bits
21709             // and work with those going forward.
21710             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21711                                            OnesOrZeroesF);
21712             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21713                                            Vector64);
21714             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21715                                         Vector32, DAG.getIntPtrConstant(0));
21716             IntVT = MVT::i32;
21717           }
21718
21719           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21720           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21721                                       DAG.getConstant(1, IntVT));
21722           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21723           return OneBitOfTruth;
21724         }
21725       }
21726     }
21727   }
21728   return SDValue();
21729 }
21730
21731 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21732 /// so it can be folded inside ANDNP.
21733 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21734   EVT VT = N->getValueType(0);
21735
21736   // Match direct AllOnes for 128 and 256-bit vectors
21737   if (ISD::isBuildVectorAllOnes(N))
21738     return true;
21739
21740   // Look through a bit convert.
21741   if (N->getOpcode() == ISD::BITCAST)
21742     N = N->getOperand(0).getNode();
21743
21744   // Sometimes the operand may come from a insert_subvector building a 256-bit
21745   // allones vector
21746   if (VT.is256BitVector() &&
21747       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21748     SDValue V1 = N->getOperand(0);
21749     SDValue V2 = N->getOperand(1);
21750
21751     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21752         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21753         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21754         ISD::isBuildVectorAllOnes(V2.getNode()))
21755       return true;
21756   }
21757
21758   return false;
21759 }
21760
21761 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21762 // register. In most cases we actually compare or select YMM-sized registers
21763 // and mixing the two types creates horrible code. This method optimizes
21764 // some of the transition sequences.
21765 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21766                                  TargetLowering::DAGCombinerInfo &DCI,
21767                                  const X86Subtarget *Subtarget) {
21768   EVT VT = N->getValueType(0);
21769   if (!VT.is256BitVector())
21770     return SDValue();
21771
21772   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21773           N->getOpcode() == ISD::ZERO_EXTEND ||
21774           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21775
21776   SDValue Narrow = N->getOperand(0);
21777   EVT NarrowVT = Narrow->getValueType(0);
21778   if (!NarrowVT.is128BitVector())
21779     return SDValue();
21780
21781   if (Narrow->getOpcode() != ISD::XOR &&
21782       Narrow->getOpcode() != ISD::AND &&
21783       Narrow->getOpcode() != ISD::OR)
21784     return SDValue();
21785
21786   SDValue N0  = Narrow->getOperand(0);
21787   SDValue N1  = Narrow->getOperand(1);
21788   SDLoc DL(Narrow);
21789
21790   // The Left side has to be a trunc.
21791   if (N0.getOpcode() != ISD::TRUNCATE)
21792     return SDValue();
21793
21794   // The type of the truncated inputs.
21795   EVT WideVT = N0->getOperand(0)->getValueType(0);
21796   if (WideVT != VT)
21797     return SDValue();
21798
21799   // The right side has to be a 'trunc' or a constant vector.
21800   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21801   ConstantSDNode *RHSConstSplat = nullptr;
21802   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21803     RHSConstSplat = RHSBV->getConstantSplatNode();
21804   if (!RHSTrunc && !RHSConstSplat)
21805     return SDValue();
21806
21807   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21808
21809   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21810     return SDValue();
21811
21812   // Set N0 and N1 to hold the inputs to the new wide operation.
21813   N0 = N0->getOperand(0);
21814   if (RHSConstSplat) {
21815     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21816                      SDValue(RHSConstSplat, 0));
21817     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21818     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21819   } else if (RHSTrunc) {
21820     N1 = N1->getOperand(0);
21821   }
21822
21823   // Generate the wide operation.
21824   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21825   unsigned Opcode = N->getOpcode();
21826   switch (Opcode) {
21827   case ISD::ANY_EXTEND:
21828     return Op;
21829   case ISD::ZERO_EXTEND: {
21830     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21831     APInt Mask = APInt::getAllOnesValue(InBits);
21832     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21833     return DAG.getNode(ISD::AND, DL, VT,
21834                        Op, DAG.getConstant(Mask, VT));
21835   }
21836   case ISD::SIGN_EXTEND:
21837     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21838                        Op, DAG.getValueType(NarrowVT));
21839   default:
21840     llvm_unreachable("Unexpected opcode");
21841   }
21842 }
21843
21844 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
21845                                  TargetLowering::DAGCombinerInfo &DCI,
21846                                  const X86Subtarget *Subtarget) {
21847   SDValue N0 = N->getOperand(0);
21848   SDValue N1 = N->getOperand(1);
21849   SDLoc DL(N);
21850
21851   // A vector zext_in_reg may be represented as a shuffle,
21852   // feeding into a bitcast (this represents anyext) feeding into
21853   // an and with a mask.
21854   // We'd like to try to combine that into a shuffle with zero
21855   // plus a bitcast, removing the and.
21856   if (N0.getOpcode() != ISD::BITCAST || 
21857       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
21858     return SDValue();
21859
21860   // The other side of the AND should be a splat of 2^C, where C
21861   // is the number of bits in the source type.
21862   if (N1.getOpcode() == ISD::BITCAST)
21863     N1 = N1.getOperand(0);
21864   if (N1.getOpcode() != ISD::BUILD_VECTOR)
21865     return SDValue();
21866   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
21867
21868   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
21869   EVT SrcType = Shuffle->getValueType(0);
21870
21871   // We expect a single-source shuffle
21872   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
21873     return SDValue();
21874
21875   unsigned SrcSize = SrcType.getScalarSizeInBits();
21876
21877   APInt SplatValue, SplatUndef;
21878   unsigned SplatBitSize;
21879   bool HasAnyUndefs;
21880   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
21881                                 SplatBitSize, HasAnyUndefs))
21882     return SDValue();
21883
21884   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
21885   // Make sure the splat matches the mask we expect
21886   if (SplatBitSize > ResSize || 
21887       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
21888     return SDValue();
21889
21890   // Make sure the input and output size make sense
21891   if (SrcSize >= ResSize || ResSize % SrcSize)
21892     return SDValue();
21893
21894   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
21895   // The number of u's between each two values depends on the ratio between
21896   // the source and dest type.
21897   unsigned ZextRatio = ResSize / SrcSize;
21898   bool IsZext = true;
21899   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
21900     if (i % ZextRatio) {
21901       if (Shuffle->getMaskElt(i) > 0) {
21902         // Expected undef
21903         IsZext = false;
21904         break;
21905       }
21906     } else {
21907       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
21908         // Expected element number
21909         IsZext = false;
21910         break;
21911       }
21912     }
21913   }
21914
21915   if (!IsZext)
21916     return SDValue();
21917
21918   // Ok, perform the transformation - replace the shuffle with
21919   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
21920   // (instead of undef) where the k elements come from the zero vector.
21921   SmallVector<int, 8> Mask;
21922   unsigned NumElems = SrcType.getVectorNumElements();
21923   for (unsigned i = 0; i < NumElems; ++i)
21924     if (i % ZextRatio)
21925       Mask.push_back(NumElems);
21926     else
21927       Mask.push_back(i / ZextRatio);
21928
21929   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
21930     Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
21931   return DAG.getNode(ISD::BITCAST, DL,  N0.getValueType(), NewShuffle);
21932 }
21933
21934 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21935                                  TargetLowering::DAGCombinerInfo &DCI,
21936                                  const X86Subtarget *Subtarget) {
21937   if (DCI.isBeforeLegalizeOps())
21938     return SDValue();
21939
21940   SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget);
21941   if (Zext.getNode())
21942     return Zext;
21943
21944   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21945   if (R.getNode())
21946     return R;
21947
21948   EVT VT = N->getValueType(0);
21949   SDValue N0 = N->getOperand(0);
21950   SDValue N1 = N->getOperand(1);
21951   SDLoc DL(N);
21952
21953   // Create BEXTR instructions
21954   // BEXTR is ((X >> imm) & (2**size-1))
21955   if (VT == MVT::i32 || VT == MVT::i64) {
21956     // Check for BEXTR.
21957     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21958         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21959       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21960       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21961       if (MaskNode && ShiftNode) {
21962         uint64_t Mask = MaskNode->getZExtValue();
21963         uint64_t Shift = ShiftNode->getZExtValue();
21964         if (isMask_64(Mask)) {
21965           uint64_t MaskSize = countPopulation(Mask);
21966           if (Shift + MaskSize <= VT.getSizeInBits())
21967             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21968                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21969         }
21970       }
21971     } // BEXTR
21972
21973     return SDValue();
21974   }
21975
21976   // Want to form ANDNP nodes:
21977   // 1) In the hopes of then easily combining them with OR and AND nodes
21978   //    to form PBLEND/PSIGN.
21979   // 2) To match ANDN packed intrinsics
21980   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21981     return SDValue();
21982
21983   // Check LHS for vnot
21984   if (N0.getOpcode() == ISD::XOR &&
21985       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21986       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21987     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21988
21989   // Check RHS for vnot
21990   if (N1.getOpcode() == ISD::XOR &&
21991       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21992       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21993     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21994
21995   return SDValue();
21996 }
21997
21998 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21999                                 TargetLowering::DAGCombinerInfo &DCI,
22000                                 const X86Subtarget *Subtarget) {
22001   if (DCI.isBeforeLegalizeOps())
22002     return SDValue();
22003
22004   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22005   if (R.getNode())
22006     return R;
22007
22008   SDValue N0 = N->getOperand(0);
22009   SDValue N1 = N->getOperand(1);
22010   EVT VT = N->getValueType(0);
22011
22012   // look for psign/blend
22013   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22014     if (!Subtarget->hasSSSE3() ||
22015         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22016       return SDValue();
22017
22018     // Canonicalize pandn to RHS
22019     if (N0.getOpcode() == X86ISD::ANDNP)
22020       std::swap(N0, N1);
22021     // or (and (m, y), (pandn m, x))
22022     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22023       SDValue Mask = N1.getOperand(0);
22024       SDValue X    = N1.getOperand(1);
22025       SDValue Y;
22026       if (N0.getOperand(0) == Mask)
22027         Y = N0.getOperand(1);
22028       if (N0.getOperand(1) == Mask)
22029         Y = N0.getOperand(0);
22030
22031       // Check to see if the mask appeared in both the AND and ANDNP and
22032       if (!Y.getNode())
22033         return SDValue();
22034
22035       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22036       // Look through mask bitcast.
22037       if (Mask.getOpcode() == ISD::BITCAST)
22038         Mask = Mask.getOperand(0);
22039       if (X.getOpcode() == ISD::BITCAST)
22040         X = X.getOperand(0);
22041       if (Y.getOpcode() == ISD::BITCAST)
22042         Y = Y.getOperand(0);
22043
22044       EVT MaskVT = Mask.getValueType();
22045
22046       // Validate that the Mask operand is a vector sra node.
22047       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22048       // there is no psrai.b
22049       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22050       unsigned SraAmt = ~0;
22051       if (Mask.getOpcode() == ISD::SRA) {
22052         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22053           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22054             SraAmt = AmtConst->getZExtValue();
22055       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22056         SDValue SraC = Mask.getOperand(1);
22057         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22058       }
22059       if ((SraAmt + 1) != EltBits)
22060         return SDValue();
22061
22062       SDLoc DL(N);
22063
22064       // Now we know we at least have a plendvb with the mask val.  See if
22065       // we can form a psignb/w/d.
22066       // psign = x.type == y.type == mask.type && y = sub(0, x);
22067       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22068           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22069           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22070         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22071                "Unsupported VT for PSIGN");
22072         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22073         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22074       }
22075       // PBLENDVB only available on SSE 4.1
22076       if (!Subtarget->hasSSE41())
22077         return SDValue();
22078
22079       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22080
22081       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22082       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22083       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22084       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22085       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22086     }
22087   }
22088
22089   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22090     return SDValue();
22091
22092   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22093   MachineFunction &MF = DAG.getMachineFunction();
22094   bool OptForSize =
22095       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22096
22097   // SHLD/SHRD instructions have lower register pressure, but on some
22098   // platforms they have higher latency than the equivalent
22099   // series of shifts/or that would otherwise be generated.
22100   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22101   // have higher latencies and we are not optimizing for size.
22102   if (!OptForSize && Subtarget->isSHLDSlow())
22103     return SDValue();
22104
22105   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22106     std::swap(N0, N1);
22107   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22108     return SDValue();
22109   if (!N0.hasOneUse() || !N1.hasOneUse())
22110     return SDValue();
22111
22112   SDValue ShAmt0 = N0.getOperand(1);
22113   if (ShAmt0.getValueType() != MVT::i8)
22114     return SDValue();
22115   SDValue ShAmt1 = N1.getOperand(1);
22116   if (ShAmt1.getValueType() != MVT::i8)
22117     return SDValue();
22118   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22119     ShAmt0 = ShAmt0.getOperand(0);
22120   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22121     ShAmt1 = ShAmt1.getOperand(0);
22122
22123   SDLoc DL(N);
22124   unsigned Opc = X86ISD::SHLD;
22125   SDValue Op0 = N0.getOperand(0);
22126   SDValue Op1 = N1.getOperand(0);
22127   if (ShAmt0.getOpcode() == ISD::SUB) {
22128     Opc = X86ISD::SHRD;
22129     std::swap(Op0, Op1);
22130     std::swap(ShAmt0, ShAmt1);
22131   }
22132
22133   unsigned Bits = VT.getSizeInBits();
22134   if (ShAmt1.getOpcode() == ISD::SUB) {
22135     SDValue Sum = ShAmt1.getOperand(0);
22136     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22137       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22138       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22139         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22140       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22141         return DAG.getNode(Opc, DL, VT,
22142                            Op0, Op1,
22143                            DAG.getNode(ISD::TRUNCATE, DL,
22144                                        MVT::i8, ShAmt0));
22145     }
22146   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22147     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22148     if (ShAmt0C &&
22149         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22150       return DAG.getNode(Opc, DL, VT,
22151                          N0.getOperand(0), N1.getOperand(0),
22152                          DAG.getNode(ISD::TRUNCATE, DL,
22153                                        MVT::i8, ShAmt0));
22154   }
22155
22156   return SDValue();
22157 }
22158
22159 // Generate NEG and CMOV for integer abs.
22160 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22161   EVT VT = N->getValueType(0);
22162
22163   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22164   // 8-bit integer abs to NEG and CMOV.
22165   if (VT.isInteger() && VT.getSizeInBits() == 8)
22166     return SDValue();
22167
22168   SDValue N0 = N->getOperand(0);
22169   SDValue N1 = N->getOperand(1);
22170   SDLoc DL(N);
22171
22172   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22173   // and change it to SUB and CMOV.
22174   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22175       N0.getOpcode() == ISD::ADD &&
22176       N0.getOperand(1) == N1 &&
22177       N1.getOpcode() == ISD::SRA &&
22178       N1.getOperand(0) == N0.getOperand(0))
22179     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22180       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22181         // Generate SUB & CMOV.
22182         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22183                                   DAG.getConstant(0, VT), N0.getOperand(0));
22184
22185         SDValue Ops[] = { N0.getOperand(0), Neg,
22186                           DAG.getConstant(X86::COND_GE, MVT::i8),
22187                           SDValue(Neg.getNode(), 1) };
22188         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22189       }
22190   return SDValue();
22191 }
22192
22193 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22194 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22195                                  TargetLowering::DAGCombinerInfo &DCI,
22196                                  const X86Subtarget *Subtarget) {
22197   if (DCI.isBeforeLegalizeOps())
22198     return SDValue();
22199
22200   if (Subtarget->hasCMov()) {
22201     SDValue RV = performIntegerAbsCombine(N, DAG);
22202     if (RV.getNode())
22203       return RV;
22204   }
22205
22206   return SDValue();
22207 }
22208
22209 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22210 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22211                                   TargetLowering::DAGCombinerInfo &DCI,
22212                                   const X86Subtarget *Subtarget) {
22213   LoadSDNode *Ld = cast<LoadSDNode>(N);
22214   EVT RegVT = Ld->getValueType(0);
22215   EVT MemVT = Ld->getMemoryVT();
22216   SDLoc dl(Ld);
22217   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22218
22219   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22220   // into two 16-byte operations.
22221   ISD::LoadExtType Ext = Ld->getExtensionType();
22222   unsigned Alignment = Ld->getAlignment();
22223   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22224   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22225       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22226     unsigned NumElems = RegVT.getVectorNumElements();
22227     if (NumElems < 2)
22228       return SDValue();
22229
22230     SDValue Ptr = Ld->getBasePtr();
22231     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22232
22233     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22234                                   NumElems/2);
22235     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22236                                 Ld->getPointerInfo(), Ld->isVolatile(),
22237                                 Ld->isNonTemporal(), Ld->isInvariant(),
22238                                 Alignment);
22239     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22240     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22241                                 Ld->getPointerInfo(), Ld->isVolatile(),
22242                                 Ld->isNonTemporal(), Ld->isInvariant(),
22243                                 std::min(16U, Alignment));
22244     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22245                              Load1.getValue(1),
22246                              Load2.getValue(1));
22247
22248     SDValue NewVec = DAG.getUNDEF(RegVT);
22249     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22250     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22251     return DCI.CombineTo(N, NewVec, TF, true);
22252   }
22253
22254   return SDValue();
22255 }
22256
22257 /// PerformMLOADCombine - Resolve extending loads
22258 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22259                                    TargetLowering::DAGCombinerInfo &DCI,
22260                                    const X86Subtarget *Subtarget) {
22261   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22262   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22263     return SDValue();
22264
22265   EVT VT = Mld->getValueType(0);
22266   unsigned NumElems = VT.getVectorNumElements();
22267   EVT LdVT = Mld->getMemoryVT();
22268   SDLoc dl(Mld);
22269
22270   assert(LdVT != VT && "Cannot extend to the same type");
22271   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22272   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22273   // From, To sizes and ElemCount must be pow of two
22274   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22275     "Unexpected size for extending masked load");
22276
22277   unsigned SizeRatio  = ToSz / FromSz;
22278   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22279
22280   // Create a type on which we perform the shuffle
22281   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22282           LdVT.getScalarType(), NumElems*SizeRatio);
22283   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22284
22285   // Convert Src0 value
22286   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22287   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22288     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22289     for (unsigned i = 0; i != NumElems; ++i)
22290       ShuffleVec[i] = i * SizeRatio;
22291
22292     // Can't shuffle using an illegal type.
22293     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22294             && "WideVecVT should be legal");
22295     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22296                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22297   }
22298   // Prepare the new mask
22299   SDValue NewMask;
22300   SDValue Mask = Mld->getMask();
22301   if (Mask.getValueType() == VT) {
22302     // Mask and original value have the same type
22303     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22304     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22305     for (unsigned i = 0; i != NumElems; ++i)
22306       ShuffleVec[i] = i * SizeRatio;
22307     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22308       ShuffleVec[i] = NumElems*SizeRatio;
22309     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22310                                    DAG.getConstant(0, WideVecVT),
22311                                    &ShuffleVec[0]);
22312   }
22313   else {
22314     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22315     unsigned WidenNumElts = NumElems*SizeRatio;
22316     unsigned MaskNumElts = VT.getVectorNumElements();
22317     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22318                                      WidenNumElts);
22319
22320     unsigned NumConcat = WidenNumElts / MaskNumElts;
22321     SmallVector<SDValue, 16> Ops(NumConcat);
22322     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22323     Ops[0] = Mask;
22324     for (unsigned i = 1; i != NumConcat; ++i)
22325       Ops[i] = ZeroVal;
22326
22327     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22328   }
22329
22330   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22331                                      Mld->getBasePtr(), NewMask, WideSrc0,
22332                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22333                                      ISD::NON_EXTLOAD);
22334   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22335   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22336
22337 }
22338 /// PerformMSTORECombine - Resolve truncating stores
22339 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22340                                     const X86Subtarget *Subtarget) {
22341   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22342   if (!Mst->isTruncatingStore())
22343     return SDValue();
22344
22345   EVT VT = Mst->getValue().getValueType();
22346   unsigned NumElems = VT.getVectorNumElements();
22347   EVT StVT = Mst->getMemoryVT();
22348   SDLoc dl(Mst);
22349
22350   assert(StVT != VT && "Cannot truncate to the same type");
22351   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22352   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22353
22354   // From, To sizes and ElemCount must be pow of two
22355   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22356     "Unexpected size for truncating masked store");
22357   // We are going to use the original vector elt for storing.
22358   // Accumulated smaller vector elements must be a multiple of the store size.
22359   assert (((NumElems * FromSz) % ToSz) == 0 &&
22360           "Unexpected ratio for truncating masked store");
22361
22362   unsigned SizeRatio  = FromSz / ToSz;
22363   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22364
22365   // Create a type on which we perform the shuffle
22366   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22367           StVT.getScalarType(), NumElems*SizeRatio);
22368
22369   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22370
22371   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22372   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22373   for (unsigned i = 0; i != NumElems; ++i)
22374     ShuffleVec[i] = i * SizeRatio;
22375
22376   // Can't shuffle using an illegal type.
22377   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22378           && "WideVecVT should be legal");
22379
22380   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22381                                         DAG.getUNDEF(WideVecVT),
22382                                         &ShuffleVec[0]);
22383
22384   SDValue NewMask;
22385   SDValue Mask = Mst->getMask();
22386   if (Mask.getValueType() == VT) {
22387     // Mask and original value have the same type
22388     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22389     for (unsigned i = 0; i != NumElems; ++i)
22390       ShuffleVec[i] = i * SizeRatio;
22391     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22392       ShuffleVec[i] = NumElems*SizeRatio;
22393     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22394                                    DAG.getConstant(0, WideVecVT),
22395                                    &ShuffleVec[0]);
22396   }
22397   else {
22398     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22399     unsigned WidenNumElts = NumElems*SizeRatio;
22400     unsigned MaskNumElts = VT.getVectorNumElements();
22401     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22402                                      WidenNumElts);
22403
22404     unsigned NumConcat = WidenNumElts / MaskNumElts;
22405     SmallVector<SDValue, 16> Ops(NumConcat);
22406     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22407     Ops[0] = Mask;
22408     for (unsigned i = 1; i != NumConcat; ++i)
22409       Ops[i] = ZeroVal;
22410
22411     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22412   }
22413
22414   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22415                             NewMask, StVT, Mst->getMemOperand(), false);
22416 }
22417 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22418 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22419                                    const X86Subtarget *Subtarget) {
22420   StoreSDNode *St = cast<StoreSDNode>(N);
22421   EVT VT = St->getValue().getValueType();
22422   EVT StVT = St->getMemoryVT();
22423   SDLoc dl(St);
22424   SDValue StoredVal = St->getOperand(1);
22425   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22426
22427   // If we are saving a concatenation of two XMM registers and 32-byte stores
22428   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22429   unsigned Alignment = St->getAlignment();
22430   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22431   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22432       StVT == VT && !IsAligned) {
22433     unsigned NumElems = VT.getVectorNumElements();
22434     if (NumElems < 2)
22435       return SDValue();
22436
22437     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22438     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22439
22440     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22441     SDValue Ptr0 = St->getBasePtr();
22442     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22443
22444     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22445                                 St->getPointerInfo(), St->isVolatile(),
22446                                 St->isNonTemporal(), Alignment);
22447     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22448                                 St->getPointerInfo(), St->isVolatile(),
22449                                 St->isNonTemporal(),
22450                                 std::min(16U, Alignment));
22451     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22452   }
22453
22454   // Optimize trunc store (of multiple scalars) to shuffle and store.
22455   // First, pack all of the elements in one place. Next, store to memory
22456   // in fewer chunks.
22457   if (St->isTruncatingStore() && VT.isVector()) {
22458     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22459     unsigned NumElems = VT.getVectorNumElements();
22460     assert(StVT != VT && "Cannot truncate to the same type");
22461     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22462     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22463
22464     // From, To sizes and ElemCount must be pow of two
22465     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22466     // We are going to use the original vector elt for storing.
22467     // Accumulated smaller vector elements must be a multiple of the store size.
22468     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22469
22470     unsigned SizeRatio  = FromSz / ToSz;
22471
22472     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22473
22474     // Create a type on which we perform the shuffle
22475     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22476             StVT.getScalarType(), NumElems*SizeRatio);
22477
22478     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22479
22480     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22481     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22482     for (unsigned i = 0; i != NumElems; ++i)
22483       ShuffleVec[i] = i * SizeRatio;
22484
22485     // Can't shuffle using an illegal type.
22486     if (!TLI.isTypeLegal(WideVecVT))
22487       return SDValue();
22488
22489     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22490                                          DAG.getUNDEF(WideVecVT),
22491                                          &ShuffleVec[0]);
22492     // At this point all of the data is stored at the bottom of the
22493     // register. We now need to save it to mem.
22494
22495     // Find the largest store unit
22496     MVT StoreType = MVT::i8;
22497     for (MVT Tp : MVT::integer_valuetypes()) {
22498       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22499         StoreType = Tp;
22500     }
22501
22502     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22503     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22504         (64 <= NumElems * ToSz))
22505       StoreType = MVT::f64;
22506
22507     // Bitcast the original vector into a vector of store-size units
22508     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22509             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22510     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22511     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22512     SmallVector<SDValue, 8> Chains;
22513     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22514                                         TLI.getPointerTy());
22515     SDValue Ptr = St->getBasePtr();
22516
22517     // Perform one or more big stores into memory.
22518     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22519       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22520                                    StoreType, ShuffWide,
22521                                    DAG.getIntPtrConstant(i));
22522       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22523                                 St->getPointerInfo(), St->isVolatile(),
22524                                 St->isNonTemporal(), St->getAlignment());
22525       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22526       Chains.push_back(Ch);
22527     }
22528
22529     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22530   }
22531
22532   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22533   // the FP state in cases where an emms may be missing.
22534   // A preferable solution to the general problem is to figure out the right
22535   // places to insert EMMS.  This qualifies as a quick hack.
22536
22537   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22538   if (VT.getSizeInBits() != 64)
22539     return SDValue();
22540
22541   const Function *F = DAG.getMachineFunction().getFunction();
22542   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22543   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22544                      && Subtarget->hasSSE2();
22545   if ((VT.isVector() ||
22546        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22547       isa<LoadSDNode>(St->getValue()) &&
22548       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22549       St->getChain().hasOneUse() && !St->isVolatile()) {
22550     SDNode* LdVal = St->getValue().getNode();
22551     LoadSDNode *Ld = nullptr;
22552     int TokenFactorIndex = -1;
22553     SmallVector<SDValue, 8> Ops;
22554     SDNode* ChainVal = St->getChain().getNode();
22555     // Must be a store of a load.  We currently handle two cases:  the load
22556     // is a direct child, and it's under an intervening TokenFactor.  It is
22557     // possible to dig deeper under nested TokenFactors.
22558     if (ChainVal == LdVal)
22559       Ld = cast<LoadSDNode>(St->getChain());
22560     else if (St->getValue().hasOneUse() &&
22561              ChainVal->getOpcode() == ISD::TokenFactor) {
22562       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22563         if (ChainVal->getOperand(i).getNode() == LdVal) {
22564           TokenFactorIndex = i;
22565           Ld = cast<LoadSDNode>(St->getValue());
22566         } else
22567           Ops.push_back(ChainVal->getOperand(i));
22568       }
22569     }
22570
22571     if (!Ld || !ISD::isNormalLoad(Ld))
22572       return SDValue();
22573
22574     // If this is not the MMX case, i.e. we are just turning i64 load/store
22575     // into f64 load/store, avoid the transformation if there are multiple
22576     // uses of the loaded value.
22577     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22578       return SDValue();
22579
22580     SDLoc LdDL(Ld);
22581     SDLoc StDL(N);
22582     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22583     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22584     // pair instead.
22585     if (Subtarget->is64Bit() || F64IsLegal) {
22586       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22587       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22588                                   Ld->getPointerInfo(), Ld->isVolatile(),
22589                                   Ld->isNonTemporal(), Ld->isInvariant(),
22590                                   Ld->getAlignment());
22591       SDValue NewChain = NewLd.getValue(1);
22592       if (TokenFactorIndex != -1) {
22593         Ops.push_back(NewChain);
22594         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22595       }
22596       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22597                           St->getPointerInfo(),
22598                           St->isVolatile(), St->isNonTemporal(),
22599                           St->getAlignment());
22600     }
22601
22602     // Otherwise, lower to two pairs of 32-bit loads / stores.
22603     SDValue LoAddr = Ld->getBasePtr();
22604     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22605                                  DAG.getConstant(4, MVT::i32));
22606
22607     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22608                                Ld->getPointerInfo(),
22609                                Ld->isVolatile(), Ld->isNonTemporal(),
22610                                Ld->isInvariant(), Ld->getAlignment());
22611     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22612                                Ld->getPointerInfo().getWithOffset(4),
22613                                Ld->isVolatile(), Ld->isNonTemporal(),
22614                                Ld->isInvariant(),
22615                                MinAlign(Ld->getAlignment(), 4));
22616
22617     SDValue NewChain = LoLd.getValue(1);
22618     if (TokenFactorIndex != -1) {
22619       Ops.push_back(LoLd);
22620       Ops.push_back(HiLd);
22621       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22622     }
22623
22624     LoAddr = St->getBasePtr();
22625     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22626                          DAG.getConstant(4, MVT::i32));
22627
22628     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22629                                 St->getPointerInfo(),
22630                                 St->isVolatile(), St->isNonTemporal(),
22631                                 St->getAlignment());
22632     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22633                                 St->getPointerInfo().getWithOffset(4),
22634                                 St->isVolatile(),
22635                                 St->isNonTemporal(),
22636                                 MinAlign(St->getAlignment(), 4));
22637     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22638   }
22639   return SDValue();
22640 }
22641
22642 /// Return 'true' if this vector operation is "horizontal"
22643 /// and return the operands for the horizontal operation in LHS and RHS.  A
22644 /// horizontal operation performs the binary operation on successive elements
22645 /// of its first operand, then on successive elements of its second operand,
22646 /// returning the resulting values in a vector.  For example, if
22647 ///   A = < float a0, float a1, float a2, float a3 >
22648 /// and
22649 ///   B = < float b0, float b1, float b2, float b3 >
22650 /// then the result of doing a horizontal operation on A and B is
22651 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22652 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22653 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22654 /// set to A, RHS to B, and the routine returns 'true'.
22655 /// Note that the binary operation should have the property that if one of the
22656 /// operands is UNDEF then the result is UNDEF.
22657 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22658   // Look for the following pattern: if
22659   //   A = < float a0, float a1, float a2, float a3 >
22660   //   B = < float b0, float b1, float b2, float b3 >
22661   // and
22662   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22663   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22664   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22665   // which is A horizontal-op B.
22666
22667   // At least one of the operands should be a vector shuffle.
22668   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22669       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22670     return false;
22671
22672   MVT VT = LHS.getSimpleValueType();
22673
22674   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22675          "Unsupported vector type for horizontal add/sub");
22676
22677   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22678   // operate independently on 128-bit lanes.
22679   unsigned NumElts = VT.getVectorNumElements();
22680   unsigned NumLanes = VT.getSizeInBits()/128;
22681   unsigned NumLaneElts = NumElts / NumLanes;
22682   assert((NumLaneElts % 2 == 0) &&
22683          "Vector type should have an even number of elements in each lane");
22684   unsigned HalfLaneElts = NumLaneElts/2;
22685
22686   // View LHS in the form
22687   //   LHS = VECTOR_SHUFFLE A, B, LMask
22688   // If LHS is not a shuffle then pretend it is the shuffle
22689   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22690   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22691   // type VT.
22692   SDValue A, B;
22693   SmallVector<int, 16> LMask(NumElts);
22694   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22695     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22696       A = LHS.getOperand(0);
22697     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22698       B = LHS.getOperand(1);
22699     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22700     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22701   } else {
22702     if (LHS.getOpcode() != ISD::UNDEF)
22703       A = LHS;
22704     for (unsigned i = 0; i != NumElts; ++i)
22705       LMask[i] = i;
22706   }
22707
22708   // Likewise, view RHS in the form
22709   //   RHS = VECTOR_SHUFFLE C, D, RMask
22710   SDValue C, D;
22711   SmallVector<int, 16> RMask(NumElts);
22712   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22713     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22714       C = RHS.getOperand(0);
22715     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22716       D = RHS.getOperand(1);
22717     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22718     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22719   } else {
22720     if (RHS.getOpcode() != ISD::UNDEF)
22721       C = RHS;
22722     for (unsigned i = 0; i != NumElts; ++i)
22723       RMask[i] = i;
22724   }
22725
22726   // Check that the shuffles are both shuffling the same vectors.
22727   if (!(A == C && B == D) && !(A == D && B == C))
22728     return false;
22729
22730   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22731   if (!A.getNode() && !B.getNode())
22732     return false;
22733
22734   // If A and B occur in reverse order in RHS, then "swap" them (which means
22735   // rewriting the mask).
22736   if (A != C)
22737     CommuteVectorShuffleMask(RMask, NumElts);
22738
22739   // At this point LHS and RHS are equivalent to
22740   //   LHS = VECTOR_SHUFFLE A, B, LMask
22741   //   RHS = VECTOR_SHUFFLE A, B, RMask
22742   // Check that the masks correspond to performing a horizontal operation.
22743   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22744     for (unsigned i = 0; i != NumLaneElts; ++i) {
22745       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22746
22747       // Ignore any UNDEF components.
22748       if (LIdx < 0 || RIdx < 0 ||
22749           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22750           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22751         continue;
22752
22753       // Check that successive elements are being operated on.  If not, this is
22754       // not a horizontal operation.
22755       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22756       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22757       if (!(LIdx == Index && RIdx == Index + 1) &&
22758           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22759         return false;
22760     }
22761   }
22762
22763   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22764   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22765   return true;
22766 }
22767
22768 /// Do target-specific dag combines on floating point adds.
22769 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22770                                   const X86Subtarget *Subtarget) {
22771   EVT VT = N->getValueType(0);
22772   SDValue LHS = N->getOperand(0);
22773   SDValue RHS = N->getOperand(1);
22774
22775   // Try to synthesize horizontal adds from adds of shuffles.
22776   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22777        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22778       isHorizontalBinOp(LHS, RHS, true))
22779     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22780   return SDValue();
22781 }
22782
22783 /// Do target-specific dag combines on floating point subs.
22784 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22785                                   const X86Subtarget *Subtarget) {
22786   EVT VT = N->getValueType(0);
22787   SDValue LHS = N->getOperand(0);
22788   SDValue RHS = N->getOperand(1);
22789
22790   // Try to synthesize horizontal subs from subs of shuffles.
22791   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22792        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22793       isHorizontalBinOp(LHS, RHS, false))
22794     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22795   return SDValue();
22796 }
22797
22798 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
22799 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22800   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22801
22802   // F[X]OR(0.0, x) -> x
22803   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22804     if (C->getValueAPF().isPosZero())
22805       return N->getOperand(1);
22806
22807   // F[X]OR(x, 0.0) -> x
22808   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22809     if (C->getValueAPF().isPosZero())
22810       return N->getOperand(0);
22811   return SDValue();
22812 }
22813
22814 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
22815 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22816   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22817
22818   // Only perform optimizations if UnsafeMath is used.
22819   if (!DAG.getTarget().Options.UnsafeFPMath)
22820     return SDValue();
22821
22822   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22823   // into FMINC and FMAXC, which are Commutative operations.
22824   unsigned NewOp = 0;
22825   switch (N->getOpcode()) {
22826     default: llvm_unreachable("unknown opcode");
22827     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22828     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22829   }
22830
22831   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22832                      N->getOperand(0), N->getOperand(1));
22833 }
22834
22835 /// Do target-specific dag combines on X86ISD::FAND nodes.
22836 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22837   // FAND(0.0, x) -> 0.0
22838   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22839     if (C->getValueAPF().isPosZero())
22840       return N->getOperand(0);
22841
22842   // FAND(x, 0.0) -> 0.0
22843   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22844     if (C->getValueAPF().isPosZero())
22845       return N->getOperand(1);
22846   
22847   return SDValue();
22848 }
22849
22850 /// Do target-specific dag combines on X86ISD::FANDN nodes
22851 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22852   // FANDN(0.0, x) -> x
22853   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22854     if (C->getValueAPF().isPosZero())
22855       return N->getOperand(1);
22856
22857   // FANDN(x, 0.0) -> 0.0
22858   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22859     if (C->getValueAPF().isPosZero())
22860       return N->getOperand(1);
22861
22862   return SDValue();
22863 }
22864
22865 static SDValue PerformBTCombine(SDNode *N,
22866                                 SelectionDAG &DAG,
22867                                 TargetLowering::DAGCombinerInfo &DCI) {
22868   // BT ignores high bits in the bit index operand.
22869   SDValue Op1 = N->getOperand(1);
22870   if (Op1.hasOneUse()) {
22871     unsigned BitWidth = Op1.getValueSizeInBits();
22872     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22873     APInt KnownZero, KnownOne;
22874     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22875                                           !DCI.isBeforeLegalizeOps());
22876     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22877     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22878         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22879       DCI.CommitTargetLoweringOpt(TLO);
22880   }
22881   return SDValue();
22882 }
22883
22884 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22885   SDValue Op = N->getOperand(0);
22886   if (Op.getOpcode() == ISD::BITCAST)
22887     Op = Op.getOperand(0);
22888   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22889   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22890       VT.getVectorElementType().getSizeInBits() ==
22891       OpVT.getVectorElementType().getSizeInBits()) {
22892     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22893   }
22894   return SDValue();
22895 }
22896
22897 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22898                                                const X86Subtarget *Subtarget) {
22899   EVT VT = N->getValueType(0);
22900   if (!VT.isVector())
22901     return SDValue();
22902
22903   SDValue N0 = N->getOperand(0);
22904   SDValue N1 = N->getOperand(1);
22905   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22906   SDLoc dl(N);
22907
22908   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22909   // both SSE and AVX2 since there is no sign-extended shift right
22910   // operation on a vector with 64-bit elements.
22911   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22912   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22913   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22914       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22915     SDValue N00 = N0.getOperand(0);
22916
22917     // EXTLOAD has a better solution on AVX2,
22918     // it may be replaced with X86ISD::VSEXT node.
22919     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22920       if (!ISD::isNormalLoad(N00.getNode()))
22921         return SDValue();
22922
22923     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22924         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22925                                   N00, N1);
22926       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22927     }
22928   }
22929   return SDValue();
22930 }
22931
22932 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22933                                   TargetLowering::DAGCombinerInfo &DCI,
22934                                   const X86Subtarget *Subtarget) {
22935   SDValue N0 = N->getOperand(0);
22936   EVT VT = N->getValueType(0);
22937
22938   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
22939   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
22940   // This exposes the sext to the sdivrem lowering, so that it directly extends
22941   // from AH (which we otherwise need to do contortions to access).
22942   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
22943       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
22944     SDLoc dl(N);
22945     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
22946     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
22947                             N0.getOperand(0), N0.getOperand(1));
22948     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
22949     return R.getValue(1);
22950   }
22951
22952   if (!DCI.isBeforeLegalizeOps())
22953     return SDValue();
22954
22955   if (!Subtarget->hasFp256())
22956     return SDValue();
22957
22958   if (VT.isVector() && VT.getSizeInBits() == 256) {
22959     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22960     if (R.getNode())
22961       return R;
22962   }
22963
22964   return SDValue();
22965 }
22966
22967 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22968                                  const X86Subtarget* Subtarget) {
22969   SDLoc dl(N);
22970   EVT VT = N->getValueType(0);
22971
22972   // Let legalize expand this if it isn't a legal type yet.
22973   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22974     return SDValue();
22975
22976   EVT ScalarVT = VT.getScalarType();
22977   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22978       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22979     return SDValue();
22980
22981   SDValue A = N->getOperand(0);
22982   SDValue B = N->getOperand(1);
22983   SDValue C = N->getOperand(2);
22984
22985   bool NegA = (A.getOpcode() == ISD::FNEG);
22986   bool NegB = (B.getOpcode() == ISD::FNEG);
22987   bool NegC = (C.getOpcode() == ISD::FNEG);
22988
22989   // Negative multiplication when NegA xor NegB
22990   bool NegMul = (NegA != NegB);
22991   if (NegA)
22992     A = A.getOperand(0);
22993   if (NegB)
22994     B = B.getOperand(0);
22995   if (NegC)
22996     C = C.getOperand(0);
22997
22998   unsigned Opcode;
22999   if (!NegMul)
23000     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23001   else
23002     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23003
23004   return DAG.getNode(Opcode, dl, VT, A, B, C);
23005 }
23006
23007 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23008                                   TargetLowering::DAGCombinerInfo &DCI,
23009                                   const X86Subtarget *Subtarget) {
23010   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23011   //           (and (i32 x86isd::setcc_carry), 1)
23012   // This eliminates the zext. This transformation is necessary because
23013   // ISD::SETCC is always legalized to i8.
23014   SDLoc dl(N);
23015   SDValue N0 = N->getOperand(0);
23016   EVT VT = N->getValueType(0);
23017
23018   if (N0.getOpcode() == ISD::AND &&
23019       N0.hasOneUse() &&
23020       N0.getOperand(0).hasOneUse()) {
23021     SDValue N00 = N0.getOperand(0);
23022     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23023       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23024       if (!C || C->getZExtValue() != 1)
23025         return SDValue();
23026       return DAG.getNode(ISD::AND, dl, VT,
23027                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23028                                      N00.getOperand(0), N00.getOperand(1)),
23029                          DAG.getConstant(1, VT));
23030     }
23031   }
23032
23033   if (N0.getOpcode() == ISD::TRUNCATE &&
23034       N0.hasOneUse() &&
23035       N0.getOperand(0).hasOneUse()) {
23036     SDValue N00 = N0.getOperand(0);
23037     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23038       return DAG.getNode(ISD::AND, dl, VT,
23039                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23040                                      N00.getOperand(0), N00.getOperand(1)),
23041                          DAG.getConstant(1, VT));
23042     }
23043   }
23044   if (VT.is256BitVector()) {
23045     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23046     if (R.getNode())
23047       return R;
23048   }
23049
23050   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23051   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23052   // This exposes the zext to the udivrem lowering, so that it directly extends
23053   // from AH (which we otherwise need to do contortions to access).
23054   if (N0.getOpcode() == ISD::UDIVREM &&
23055       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23056       (VT == MVT::i32 || VT == MVT::i64)) {
23057     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23058     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23059                             N0.getOperand(0), N0.getOperand(1));
23060     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23061     return R.getValue(1);
23062   }
23063
23064   return SDValue();
23065 }
23066
23067 // Optimize x == -y --> x+y == 0
23068 //          x != -y --> x+y != 0
23069 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23070                                       const X86Subtarget* Subtarget) {
23071   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23072   SDValue LHS = N->getOperand(0);
23073   SDValue RHS = N->getOperand(1);
23074   EVT VT = N->getValueType(0);
23075   SDLoc DL(N);
23076
23077   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23078     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23079       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23080         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
23081                                    LHS.getValueType(), RHS, LHS.getOperand(1));
23082         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
23083                             addV, DAG.getConstant(0, addV.getValueType()), CC);
23084       }
23085   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23086     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23087       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23088         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
23089                                    RHS.getValueType(), LHS, RHS.getOperand(1));
23090         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
23091                             addV, DAG.getConstant(0, addV.getValueType()), CC);
23092       }
23093
23094   if (VT.getScalarType() == MVT::i1) {
23095     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23096       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
23097     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
23098     if (!IsSEXT0 && !IsVZero0)
23099       return SDValue();
23100     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
23101       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
23102     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23103
23104     if (!IsSEXT1 && !IsVZero1)
23105       return SDValue();
23106
23107     if (IsSEXT0 && IsVZero1) {
23108       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
23109       if (CC == ISD::SETEQ)
23110         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23111       return LHS.getOperand(0);
23112     }
23113     if (IsSEXT1 && IsVZero0) {
23114       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
23115       if (CC == ISD::SETEQ)
23116         return DAG.getNOT(DL, RHS.getOperand(0), VT);
23117       return RHS.getOperand(0);
23118     }
23119   }
23120
23121   return SDValue();
23122 }
23123
23124 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23125                                          SelectionDAG &DAG) {
23126   SDLoc dl(Load);
23127   MVT VT = Load->getSimpleValueType(0);
23128   MVT EVT = VT.getVectorElementType();
23129   SDValue Addr = Load->getOperand(1);
23130   SDValue NewAddr = DAG.getNode(
23131       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23132       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23133
23134   SDValue NewLoad =
23135       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23136                   DAG.getMachineFunction().getMachineMemOperand(
23137                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23138   return NewLoad;
23139 }
23140
23141 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23142                                       const X86Subtarget *Subtarget) {
23143   SDLoc dl(N);
23144   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23145   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23146          "X86insertps is only defined for v4x32");
23147
23148   SDValue Ld = N->getOperand(1);
23149   if (MayFoldLoad(Ld)) {
23150     // Extract the countS bits from the immediate so we can get the proper
23151     // address when narrowing the vector load to a specific element.
23152     // When the second source op is a memory address, insertps doesn't use
23153     // countS and just gets an f32 from that address.
23154     unsigned DestIndex =
23155         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23156     
23157     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23158
23159     // Create this as a scalar to vector to match the instruction pattern.
23160     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23161     // countS bits are ignored when loading from memory on insertps, which
23162     // means we don't need to explicitly set them to 0.
23163     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23164                        LoadScalarToVector, N->getOperand(2));
23165   }
23166   return SDValue();
23167 }
23168
23169 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23170   SDValue V0 = N->getOperand(0);
23171   SDValue V1 = N->getOperand(1);
23172   SDLoc DL(N);
23173   EVT VT = N->getValueType(0);
23174
23175   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23176   // operands and changing the mask to 1. This saves us a bunch of
23177   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23178   // x86InstrInfo knows how to commute this back after instruction selection
23179   // if it would help register allocation.
23180   
23181   // TODO: If optimizing for size or a processor that doesn't suffer from
23182   // partial register update stalls, this should be transformed into a MOVSD
23183   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23184
23185   if (VT == MVT::v2f64)
23186     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23187       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23188         SDValue NewMask = DAG.getConstant(1, MVT::i8);
23189         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23190       }
23191
23192   return SDValue();
23193 }
23194
23195 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23196 // as "sbb reg,reg", since it can be extended without zext and produces
23197 // an all-ones bit which is more useful than 0/1 in some cases.
23198 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23199                                MVT VT) {
23200   if (VT == MVT::i8)
23201     return DAG.getNode(ISD::AND, DL, VT,
23202                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23203                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23204                        DAG.getConstant(1, VT));
23205   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23206   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23207                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23208                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23209 }
23210
23211 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23212 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23213                                    TargetLowering::DAGCombinerInfo &DCI,
23214                                    const X86Subtarget *Subtarget) {
23215   SDLoc DL(N);
23216   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23217   SDValue EFLAGS = N->getOperand(1);
23218
23219   if (CC == X86::COND_A) {
23220     // Try to convert COND_A into COND_B in an attempt to facilitate
23221     // materializing "setb reg".
23222     //
23223     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23224     // cannot take an immediate as its first operand.
23225     //
23226     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23227         EFLAGS.getValueType().isInteger() &&
23228         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23229       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23230                                    EFLAGS.getNode()->getVTList(),
23231                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23232       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23233       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23234     }
23235   }
23236
23237   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23238   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23239   // cases.
23240   if (CC == X86::COND_B)
23241     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23242
23243   SDValue Flags;
23244
23245   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23246   if (Flags.getNode()) {
23247     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23248     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23249   }
23250
23251   return SDValue();
23252 }
23253
23254 // Optimize branch condition evaluation.
23255 //
23256 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23257                                     TargetLowering::DAGCombinerInfo &DCI,
23258                                     const X86Subtarget *Subtarget) {
23259   SDLoc DL(N);
23260   SDValue Chain = N->getOperand(0);
23261   SDValue Dest = N->getOperand(1);
23262   SDValue EFLAGS = N->getOperand(3);
23263   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23264
23265   SDValue Flags;
23266
23267   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23268   if (Flags.getNode()) {
23269     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23270     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23271                        Flags);
23272   }
23273
23274   return SDValue();
23275 }
23276
23277 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23278                                                          SelectionDAG &DAG) {
23279   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23280   // optimize away operation when it's from a constant.
23281   //
23282   // The general transformation is:
23283   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23284   //       AND(VECTOR_CMP(x,y), constant2)
23285   //    constant2 = UNARYOP(constant)
23286
23287   // Early exit if this isn't a vector operation, the operand of the
23288   // unary operation isn't a bitwise AND, or if the sizes of the operations
23289   // aren't the same.
23290   EVT VT = N->getValueType(0);
23291   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23292       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23293       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23294     return SDValue();
23295
23296   // Now check that the other operand of the AND is a constant. We could
23297   // make the transformation for non-constant splats as well, but it's unclear
23298   // that would be a benefit as it would not eliminate any operations, just
23299   // perform one more step in scalar code before moving to the vector unit.
23300   if (BuildVectorSDNode *BV =
23301           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23302     // Bail out if the vector isn't a constant.
23303     if (!BV->isConstant())
23304       return SDValue();
23305
23306     // Everything checks out. Build up the new and improved node.
23307     SDLoc DL(N);
23308     EVT IntVT = BV->getValueType(0);
23309     // Create a new constant of the appropriate type for the transformed
23310     // DAG.
23311     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23312     // The AND node needs bitcasts to/from an integer vector type around it.
23313     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23314     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23315                                  N->getOperand(0)->getOperand(0), MaskConst);
23316     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23317     return Res;
23318   }
23319
23320   return SDValue();
23321 }
23322
23323 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23324                                         const X86Subtarget *Subtarget) {
23325   // First try to optimize away the conversion entirely when it's
23326   // conditionally from a constant. Vectors only.
23327   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23328   if (Res != SDValue())
23329     return Res;
23330
23331   // Now move on to more general possibilities.
23332   SDValue Op0 = N->getOperand(0);
23333   EVT InVT = Op0->getValueType(0);
23334
23335   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23336   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23337     SDLoc dl(N);
23338     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23339     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23340     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23341   }
23342
23343   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23344   // a 32-bit target where SSE doesn't support i64->FP operations.
23345   if (Op0.getOpcode() == ISD::LOAD) {
23346     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23347     EVT VT = Ld->getValueType(0);
23348     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23349         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23350         !Subtarget->is64Bit() && VT == MVT::i64) {
23351       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23352           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23353       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23354       return FILDChain;
23355     }
23356   }
23357   return SDValue();
23358 }
23359
23360 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23361 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23362                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23363   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23364   // the result is either zero or one (depending on the input carry bit).
23365   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23366   if (X86::isZeroNode(N->getOperand(0)) &&
23367       X86::isZeroNode(N->getOperand(1)) &&
23368       // We don't have a good way to replace an EFLAGS use, so only do this when
23369       // dead right now.
23370       SDValue(N, 1).use_empty()) {
23371     SDLoc DL(N);
23372     EVT VT = N->getValueType(0);
23373     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23374     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23375                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23376                                            DAG.getConstant(X86::COND_B,MVT::i8),
23377                                            N->getOperand(2)),
23378                                DAG.getConstant(1, VT));
23379     return DCI.CombineTo(N, Res1, CarryOut);
23380   }
23381
23382   return SDValue();
23383 }
23384
23385 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23386 //      (add Y, (setne X, 0)) -> sbb -1, Y
23387 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23388 //      (sub (setne X, 0), Y) -> adc -1, Y
23389 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23390   SDLoc DL(N);
23391
23392   // Look through ZExts.
23393   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23394   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23395     return SDValue();
23396
23397   SDValue SetCC = Ext.getOperand(0);
23398   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23399     return SDValue();
23400
23401   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23402   if (CC != X86::COND_E && CC != X86::COND_NE)
23403     return SDValue();
23404
23405   SDValue Cmp = SetCC.getOperand(1);
23406   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23407       !X86::isZeroNode(Cmp.getOperand(1)) ||
23408       !Cmp.getOperand(0).getValueType().isInteger())
23409     return SDValue();
23410
23411   SDValue CmpOp0 = Cmp.getOperand(0);
23412   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23413                                DAG.getConstant(1, CmpOp0.getValueType()));
23414
23415   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23416   if (CC == X86::COND_NE)
23417     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23418                        DL, OtherVal.getValueType(), OtherVal,
23419                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23420   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23421                      DL, OtherVal.getValueType(), OtherVal,
23422                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23423 }
23424
23425 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23426 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23427                                  const X86Subtarget *Subtarget) {
23428   EVT VT = N->getValueType(0);
23429   SDValue Op0 = N->getOperand(0);
23430   SDValue Op1 = N->getOperand(1);
23431
23432   // Try to synthesize horizontal adds from adds of shuffles.
23433   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23434        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23435       isHorizontalBinOp(Op0, Op1, true))
23436     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23437
23438   return OptimizeConditionalInDecrement(N, DAG);
23439 }
23440
23441 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23442                                  const X86Subtarget *Subtarget) {
23443   SDValue Op0 = N->getOperand(0);
23444   SDValue Op1 = N->getOperand(1);
23445
23446   // X86 can't encode an immediate LHS of a sub. See if we can push the
23447   // negation into a preceding instruction.
23448   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23449     // If the RHS of the sub is a XOR with one use and a constant, invert the
23450     // immediate. Then add one to the LHS of the sub so we can turn
23451     // X-Y -> X+~Y+1, saving one register.
23452     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23453         isa<ConstantSDNode>(Op1.getOperand(1))) {
23454       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23455       EVT VT = Op0.getValueType();
23456       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23457                                    Op1.getOperand(0),
23458                                    DAG.getConstant(~XorC, VT));
23459       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23460                          DAG.getConstant(C->getAPIntValue()+1, VT));
23461     }
23462   }
23463
23464   // Try to synthesize horizontal adds from adds of shuffles.
23465   EVT VT = N->getValueType(0);
23466   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23467        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23468       isHorizontalBinOp(Op0, Op1, true))
23469     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23470
23471   return OptimizeConditionalInDecrement(N, DAG);
23472 }
23473
23474 /// performVZEXTCombine - Performs build vector combines
23475 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23476                                    TargetLowering::DAGCombinerInfo &DCI,
23477                                    const X86Subtarget *Subtarget) {
23478   SDLoc DL(N);
23479   MVT VT = N->getSimpleValueType(0);
23480   SDValue Op = N->getOperand(0);
23481   MVT OpVT = Op.getSimpleValueType();
23482   MVT OpEltVT = OpVT.getVectorElementType();
23483   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23484
23485   // (vzext (bitcast (vzext (x)) -> (vzext x)
23486   SDValue V = Op;
23487   while (V.getOpcode() == ISD::BITCAST)
23488     V = V.getOperand(0);
23489
23490   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23491     MVT InnerVT = V.getSimpleValueType();
23492     MVT InnerEltVT = InnerVT.getVectorElementType();
23493
23494     // If the element sizes match exactly, we can just do one larger vzext. This
23495     // is always an exact type match as vzext operates on integer types.
23496     if (OpEltVT == InnerEltVT) {
23497       assert(OpVT == InnerVT && "Types must match for vzext!");
23498       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23499     }
23500
23501     // The only other way we can combine them is if only a single element of the
23502     // inner vzext is used in the input to the outer vzext.
23503     if (InnerEltVT.getSizeInBits() < InputBits)
23504       return SDValue();
23505
23506     // In this case, the inner vzext is completely dead because we're going to
23507     // only look at bits inside of the low element. Just do the outer vzext on
23508     // a bitcast of the input to the inner.
23509     return DAG.getNode(X86ISD::VZEXT, DL, VT,
23510                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23511   }
23512
23513   // Check if we can bypass extracting and re-inserting an element of an input
23514   // vector. Essentialy:
23515   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23516   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23517       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23518       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23519     SDValue ExtractedV = V.getOperand(0);
23520     SDValue OrigV = ExtractedV.getOperand(0);
23521     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23522       if (ExtractIdx->getZExtValue() == 0) {
23523         MVT OrigVT = OrigV.getSimpleValueType();
23524         // Extract a subvector if necessary...
23525         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23526           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23527           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23528                                     OrigVT.getVectorNumElements() / Ratio);
23529           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23530                               DAG.getIntPtrConstant(0));
23531         }
23532         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23533         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23534       }
23535   }
23536
23537   return SDValue();
23538 }
23539
23540 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23541                                              DAGCombinerInfo &DCI) const {
23542   SelectionDAG &DAG = DCI.DAG;
23543   switch (N->getOpcode()) {
23544   default: break;
23545   case ISD::EXTRACT_VECTOR_ELT:
23546     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23547   case ISD::VSELECT:
23548   case ISD::SELECT:
23549   case X86ISD::SHRUNKBLEND:
23550     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23551   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
23552   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23553   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23554   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23555   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23556   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23557   case ISD::SHL:
23558   case ISD::SRA:
23559   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23560   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23561   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23562   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23563   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23564   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23565   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23566   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
23567   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23568   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23569   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23570   case X86ISD::FXOR:
23571   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23572   case X86ISD::FMIN:
23573   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23574   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23575   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23576   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23577   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23578   case ISD::ANY_EXTEND:
23579   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23580   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23581   case ISD::SIGN_EXTEND_INREG:
23582     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23583   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23584   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23585   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23586   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23587   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23588   case X86ISD::SHUFP:       // Handle all target specific shuffles
23589   case X86ISD::PALIGNR:
23590   case X86ISD::UNPCKH:
23591   case X86ISD::UNPCKL:
23592   case X86ISD::MOVHLPS:
23593   case X86ISD::MOVLHPS:
23594   case X86ISD::PSHUFB:
23595   case X86ISD::PSHUFD:
23596   case X86ISD::PSHUFHW:
23597   case X86ISD::PSHUFLW:
23598   case X86ISD::MOVSS:
23599   case X86ISD::MOVSD:
23600   case X86ISD::VPERMILPI:
23601   case X86ISD::VPERM2X128:
23602   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23603   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23604   case ISD::INTRINSIC_WO_CHAIN:
23605     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23606   case X86ISD::INSERTPS: {
23607     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23608       return PerformINSERTPSCombine(N, DAG, Subtarget);
23609     break;
23610   }
23611   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
23612   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23613   }
23614
23615   return SDValue();
23616 }
23617
23618 /// isTypeDesirableForOp - Return true if the target has native support for
23619 /// the specified value type and it is 'desirable' to use the type for the
23620 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23621 /// instruction encodings are longer and some i16 instructions are slow.
23622 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23623   if (!isTypeLegal(VT))
23624     return false;
23625   if (VT != MVT::i16)
23626     return true;
23627
23628   switch (Opc) {
23629   default:
23630     return true;
23631   case ISD::LOAD:
23632   case ISD::SIGN_EXTEND:
23633   case ISD::ZERO_EXTEND:
23634   case ISD::ANY_EXTEND:
23635   case ISD::SHL:
23636   case ISD::SRL:
23637   case ISD::SUB:
23638   case ISD::ADD:
23639   case ISD::MUL:
23640   case ISD::AND:
23641   case ISD::OR:
23642   case ISD::XOR:
23643     return false;
23644   }
23645 }
23646
23647 /// IsDesirableToPromoteOp - This method query the target whether it is
23648 /// beneficial for dag combiner to promote the specified node. If true, it
23649 /// should return the desired promotion type by reference.
23650 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23651   EVT VT = Op.getValueType();
23652   if (VT != MVT::i16)
23653     return false;
23654
23655   bool Promote = false;
23656   bool Commute = false;
23657   switch (Op.getOpcode()) {
23658   default: break;
23659   case ISD::LOAD: {
23660     LoadSDNode *LD = cast<LoadSDNode>(Op);
23661     // If the non-extending load has a single use and it's not live out, then it
23662     // might be folded.
23663     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23664                                                      Op.hasOneUse()*/) {
23665       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23666              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23667         // The only case where we'd want to promote LOAD (rather then it being
23668         // promoted as an operand is when it's only use is liveout.
23669         if (UI->getOpcode() != ISD::CopyToReg)
23670           return false;
23671       }
23672     }
23673     Promote = true;
23674     break;
23675   }
23676   case ISD::SIGN_EXTEND:
23677   case ISD::ZERO_EXTEND:
23678   case ISD::ANY_EXTEND:
23679     Promote = true;
23680     break;
23681   case ISD::SHL:
23682   case ISD::SRL: {
23683     SDValue N0 = Op.getOperand(0);
23684     // Look out for (store (shl (load), x)).
23685     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23686       return false;
23687     Promote = true;
23688     break;
23689   }
23690   case ISD::ADD:
23691   case ISD::MUL:
23692   case ISD::AND:
23693   case ISD::OR:
23694   case ISD::XOR:
23695     Commute = true;
23696     // fallthrough
23697   case ISD::SUB: {
23698     SDValue N0 = Op.getOperand(0);
23699     SDValue N1 = Op.getOperand(1);
23700     if (!Commute && MayFoldLoad(N1))
23701       return false;
23702     // Avoid disabling potential load folding opportunities.
23703     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23704       return false;
23705     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23706       return false;
23707     Promote = true;
23708   }
23709   }
23710
23711   PVT = MVT::i32;
23712   return Promote;
23713 }
23714
23715 //===----------------------------------------------------------------------===//
23716 //                           X86 Inline Assembly Support
23717 //===----------------------------------------------------------------------===//
23718
23719 // Helper to match a string separated by whitespace.
23720 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
23721   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
23722
23723   for (StringRef Piece : Pieces) {
23724     if (!S.startswith(Piece)) // Check if the piece matches.
23725       return false;
23726
23727     S = S.substr(Piece.size());
23728     StringRef::size_type Pos = S.find_first_not_of(" \t");
23729     if (Pos == 0) // We matched a prefix.
23730       return false;
23731
23732     S = S.substr(Pos);
23733   }
23734
23735   return S.empty();
23736 }
23737
23738 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23739
23740   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23741     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23742         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23743         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23744
23745       if (AsmPieces.size() == 3)
23746         return true;
23747       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23748         return true;
23749     }
23750   }
23751   return false;
23752 }
23753
23754 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23755   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23756
23757   std::string AsmStr = IA->getAsmString();
23758
23759   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23760   if (!Ty || Ty->getBitWidth() % 16 != 0)
23761     return false;
23762
23763   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23764   SmallVector<StringRef, 4> AsmPieces;
23765   SplitString(AsmStr, AsmPieces, ";\n");
23766
23767   switch (AsmPieces.size()) {
23768   default: return false;
23769   case 1:
23770     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23771     // we will turn this bswap into something that will be lowered to logical
23772     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23773     // lower so don't worry about this.
23774     // bswap $0
23775     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
23776         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
23777         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
23778         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
23779         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
23780         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
23781       // No need to check constraints, nothing other than the equivalent of
23782       // "=r,0" would be valid here.
23783       return IntrinsicLowering::LowerToByteSwap(CI);
23784     }
23785
23786     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23787     if (CI->getType()->isIntegerTy(16) &&
23788         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23789         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
23790          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
23791       AsmPieces.clear();
23792       const std::string &ConstraintsStr = IA->getConstraintString();
23793       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23794       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23795       if (clobbersFlagRegisters(AsmPieces))
23796         return IntrinsicLowering::LowerToByteSwap(CI);
23797     }
23798     break;
23799   case 3:
23800     if (CI->getType()->isIntegerTy(32) &&
23801         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23802         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
23803         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
23804         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
23805       AsmPieces.clear();
23806       const std::string &ConstraintsStr = IA->getConstraintString();
23807       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23808       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23809       if (clobbersFlagRegisters(AsmPieces))
23810         return IntrinsicLowering::LowerToByteSwap(CI);
23811     }
23812
23813     if (CI->getType()->isIntegerTy(64)) {
23814       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23815       if (Constraints.size() >= 2 &&
23816           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23817           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23818         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23819         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
23820             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
23821             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
23822           return IntrinsicLowering::LowerToByteSwap(CI);
23823       }
23824     }
23825     break;
23826   }
23827   return false;
23828 }
23829
23830 /// getConstraintType - Given a constraint letter, return the type of
23831 /// constraint it is for this target.
23832 X86TargetLowering::ConstraintType
23833 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23834   if (Constraint.size() == 1) {
23835     switch (Constraint[0]) {
23836     case 'R':
23837     case 'q':
23838     case 'Q':
23839     case 'f':
23840     case 't':
23841     case 'u':
23842     case 'y':
23843     case 'x':
23844     case 'Y':
23845     case 'l':
23846       return C_RegisterClass;
23847     case 'a':
23848     case 'b':
23849     case 'c':
23850     case 'd':
23851     case 'S':
23852     case 'D':
23853     case 'A':
23854       return C_Register;
23855     case 'I':
23856     case 'J':
23857     case 'K':
23858     case 'L':
23859     case 'M':
23860     case 'N':
23861     case 'G':
23862     case 'C':
23863     case 'e':
23864     case 'Z':
23865       return C_Other;
23866     default:
23867       break;
23868     }
23869   }
23870   return TargetLowering::getConstraintType(Constraint);
23871 }
23872
23873 /// Examine constraint type and operand type and determine a weight value.
23874 /// This object must already have been set up with the operand type
23875 /// and the current alternative constraint selected.
23876 TargetLowering::ConstraintWeight
23877   X86TargetLowering::getSingleConstraintMatchWeight(
23878     AsmOperandInfo &info, const char *constraint) const {
23879   ConstraintWeight weight = CW_Invalid;
23880   Value *CallOperandVal = info.CallOperandVal;
23881     // If we don't have a value, we can't do a match,
23882     // but allow it at the lowest weight.
23883   if (!CallOperandVal)
23884     return CW_Default;
23885   Type *type = CallOperandVal->getType();
23886   // Look at the constraint type.
23887   switch (*constraint) {
23888   default:
23889     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23890   case 'R':
23891   case 'q':
23892   case 'Q':
23893   case 'a':
23894   case 'b':
23895   case 'c':
23896   case 'd':
23897   case 'S':
23898   case 'D':
23899   case 'A':
23900     if (CallOperandVal->getType()->isIntegerTy())
23901       weight = CW_SpecificReg;
23902     break;
23903   case 'f':
23904   case 't':
23905   case 'u':
23906     if (type->isFloatingPointTy())
23907       weight = CW_SpecificReg;
23908     break;
23909   case 'y':
23910     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23911       weight = CW_SpecificReg;
23912     break;
23913   case 'x':
23914   case 'Y':
23915     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23916         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23917       weight = CW_Register;
23918     break;
23919   case 'I':
23920     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23921       if (C->getZExtValue() <= 31)
23922         weight = CW_Constant;
23923     }
23924     break;
23925   case 'J':
23926     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23927       if (C->getZExtValue() <= 63)
23928         weight = CW_Constant;
23929     }
23930     break;
23931   case 'K':
23932     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23933       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23934         weight = CW_Constant;
23935     }
23936     break;
23937   case 'L':
23938     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23939       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23940         weight = CW_Constant;
23941     }
23942     break;
23943   case 'M':
23944     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23945       if (C->getZExtValue() <= 3)
23946         weight = CW_Constant;
23947     }
23948     break;
23949   case 'N':
23950     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23951       if (C->getZExtValue() <= 0xff)
23952         weight = CW_Constant;
23953     }
23954     break;
23955   case 'G':
23956   case 'C':
23957     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23958       weight = CW_Constant;
23959     }
23960     break;
23961   case 'e':
23962     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23963       if ((C->getSExtValue() >= -0x80000000LL) &&
23964           (C->getSExtValue() <= 0x7fffffffLL))
23965         weight = CW_Constant;
23966     }
23967     break;
23968   case 'Z':
23969     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23970       if (C->getZExtValue() <= 0xffffffff)
23971         weight = CW_Constant;
23972     }
23973     break;
23974   }
23975   return weight;
23976 }
23977
23978 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23979 /// with another that has more specific requirements based on the type of the
23980 /// corresponding operand.
23981 const char *X86TargetLowering::
23982 LowerXConstraint(EVT ConstraintVT) const {
23983   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23984   // 'f' like normal targets.
23985   if (ConstraintVT.isFloatingPoint()) {
23986     if (Subtarget->hasSSE2())
23987       return "Y";
23988     if (Subtarget->hasSSE1())
23989       return "x";
23990   }
23991
23992   return TargetLowering::LowerXConstraint(ConstraintVT);
23993 }
23994
23995 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23996 /// vector.  If it is invalid, don't add anything to Ops.
23997 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23998                                                      std::string &Constraint,
23999                                                      std::vector<SDValue>&Ops,
24000                                                      SelectionDAG &DAG) const {
24001   SDValue Result;
24002
24003   // Only support length 1 constraints for now.
24004   if (Constraint.length() > 1) return;
24005
24006   char ConstraintLetter = Constraint[0];
24007   switch (ConstraintLetter) {
24008   default: break;
24009   case 'I':
24010     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24011       if (C->getZExtValue() <= 31) {
24012         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24013         break;
24014       }
24015     }
24016     return;
24017   case 'J':
24018     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24019       if (C->getZExtValue() <= 63) {
24020         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24021         break;
24022       }
24023     }
24024     return;
24025   case 'K':
24026     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24027       if (isInt<8>(C->getSExtValue())) {
24028         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24029         break;
24030       }
24031     }
24032     return;
24033   case 'L':
24034     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24035       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24036           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24037         Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24038         break;
24039       }
24040     }
24041     return;
24042   case 'M':
24043     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24044       if (C->getZExtValue() <= 3) {
24045         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24046         break;
24047       }
24048     }
24049     return;
24050   case 'N':
24051     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24052       if (C->getZExtValue() <= 255) {
24053         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24054         break;
24055       }
24056     }
24057     return;
24058   case 'O':
24059     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24060       if (C->getZExtValue() <= 127) {
24061         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24062         break;
24063       }
24064     }
24065     return;
24066   case 'e': {
24067     // 32-bit signed value
24068     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24069       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24070                                            C->getSExtValue())) {
24071         // Widen to 64 bits here to get it sign extended.
24072         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24073         break;
24074       }
24075     // FIXME gcc accepts some relocatable values here too, but only in certain
24076     // memory models; it's complicated.
24077     }
24078     return;
24079   }
24080   case 'Z': {
24081     // 32-bit unsigned value
24082     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24083       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24084                                            C->getZExtValue())) {
24085         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24086         break;
24087       }
24088     }
24089     // FIXME gcc accepts some relocatable values here too, but only in certain
24090     // memory models; it's complicated.
24091     return;
24092   }
24093   case 'i': {
24094     // Literal immediates are always ok.
24095     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24096       // Widen to 64 bits here to get it sign extended.
24097       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24098       break;
24099     }
24100
24101     // In any sort of PIC mode addresses need to be computed at runtime by
24102     // adding in a register or some sort of table lookup.  These can't
24103     // be used as immediates.
24104     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24105       return;
24106
24107     // If we are in non-pic codegen mode, we allow the address of a global (with
24108     // an optional displacement) to be used with 'i'.
24109     GlobalAddressSDNode *GA = nullptr;
24110     int64_t Offset = 0;
24111
24112     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24113     while (1) {
24114       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24115         Offset += GA->getOffset();
24116         break;
24117       } else if (Op.getOpcode() == ISD::ADD) {
24118         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24119           Offset += C->getZExtValue();
24120           Op = Op.getOperand(0);
24121           continue;
24122         }
24123       } else if (Op.getOpcode() == ISD::SUB) {
24124         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24125           Offset += -C->getZExtValue();
24126           Op = Op.getOperand(0);
24127           continue;
24128         }
24129       }
24130
24131       // Otherwise, this isn't something we can handle, reject it.
24132       return;
24133     }
24134
24135     const GlobalValue *GV = GA->getGlobal();
24136     // If we require an extra load to get this address, as in PIC mode, we
24137     // can't accept it.
24138     if (isGlobalStubReference(
24139             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24140       return;
24141
24142     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24143                                         GA->getValueType(0), Offset);
24144     break;
24145   }
24146   }
24147
24148   if (Result.getNode()) {
24149     Ops.push_back(Result);
24150     return;
24151   }
24152   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24153 }
24154
24155 std::pair<unsigned, const TargetRegisterClass *>
24156 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24157                                                 const std::string &Constraint,
24158                                                 MVT VT) const {
24159   // First, see if this is a constraint that directly corresponds to an LLVM
24160   // register class.
24161   if (Constraint.size() == 1) {
24162     // GCC Constraint Letters
24163     switch (Constraint[0]) {
24164     default: break;
24165       // TODO: Slight differences here in allocation order and leaving
24166       // RIP in the class. Do they matter any more here than they do
24167       // in the normal allocation?
24168     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24169       if (Subtarget->is64Bit()) {
24170         if (VT == MVT::i32 || VT == MVT::f32)
24171           return std::make_pair(0U, &X86::GR32RegClass);
24172         if (VT == MVT::i16)
24173           return std::make_pair(0U, &X86::GR16RegClass);
24174         if (VT == MVT::i8 || VT == MVT::i1)
24175           return std::make_pair(0U, &X86::GR8RegClass);
24176         if (VT == MVT::i64 || VT == MVT::f64)
24177           return std::make_pair(0U, &X86::GR64RegClass);
24178         break;
24179       }
24180       // 32-bit fallthrough
24181     case 'Q':   // Q_REGS
24182       if (VT == MVT::i32 || VT == MVT::f32)
24183         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24184       if (VT == MVT::i16)
24185         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24186       if (VT == MVT::i8 || VT == MVT::i1)
24187         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24188       if (VT == MVT::i64)
24189         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24190       break;
24191     case 'r':   // GENERAL_REGS
24192     case 'l':   // INDEX_REGS
24193       if (VT == MVT::i8 || VT == MVT::i1)
24194         return std::make_pair(0U, &X86::GR8RegClass);
24195       if (VT == MVT::i16)
24196         return std::make_pair(0U, &X86::GR16RegClass);
24197       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24198         return std::make_pair(0U, &X86::GR32RegClass);
24199       return std::make_pair(0U, &X86::GR64RegClass);
24200     case 'R':   // LEGACY_REGS
24201       if (VT == MVT::i8 || VT == MVT::i1)
24202         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24203       if (VT == MVT::i16)
24204         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24205       if (VT == MVT::i32 || !Subtarget->is64Bit())
24206         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24207       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24208     case 'f':  // FP Stack registers.
24209       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24210       // value to the correct fpstack register class.
24211       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24212         return std::make_pair(0U, &X86::RFP32RegClass);
24213       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24214         return std::make_pair(0U, &X86::RFP64RegClass);
24215       return std::make_pair(0U, &X86::RFP80RegClass);
24216     case 'y':   // MMX_REGS if MMX allowed.
24217       if (!Subtarget->hasMMX()) break;
24218       return std::make_pair(0U, &X86::VR64RegClass);
24219     case 'Y':   // SSE_REGS if SSE2 allowed
24220       if (!Subtarget->hasSSE2()) break;
24221       // FALL THROUGH.
24222     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24223       if (!Subtarget->hasSSE1()) break;
24224
24225       switch (VT.SimpleTy) {
24226       default: break;
24227       // Scalar SSE types.
24228       case MVT::f32:
24229       case MVT::i32:
24230         return std::make_pair(0U, &X86::FR32RegClass);
24231       case MVT::f64:
24232       case MVT::i64:
24233         return std::make_pair(0U, &X86::FR64RegClass);
24234       // Vector types.
24235       case MVT::v16i8:
24236       case MVT::v8i16:
24237       case MVT::v4i32:
24238       case MVT::v2i64:
24239       case MVT::v4f32:
24240       case MVT::v2f64:
24241         return std::make_pair(0U, &X86::VR128RegClass);
24242       // AVX types.
24243       case MVT::v32i8:
24244       case MVT::v16i16:
24245       case MVT::v8i32:
24246       case MVT::v4i64:
24247       case MVT::v8f32:
24248       case MVT::v4f64:
24249         return std::make_pair(0U, &X86::VR256RegClass);
24250       case MVT::v8f64:
24251       case MVT::v16f32:
24252       case MVT::v16i32:
24253       case MVT::v8i64:
24254         return std::make_pair(0U, &X86::VR512RegClass);
24255       }
24256       break;
24257     }
24258   }
24259
24260   // Use the default implementation in TargetLowering to convert the register
24261   // constraint into a member of a register class.
24262   std::pair<unsigned, const TargetRegisterClass*> Res;
24263   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24264
24265   // Not found as a standard register?
24266   if (!Res.second) {
24267     // Map st(0) -> st(7) -> ST0
24268     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24269         tolower(Constraint[1]) == 's' &&
24270         tolower(Constraint[2]) == 't' &&
24271         Constraint[3] == '(' &&
24272         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24273         Constraint[5] == ')' &&
24274         Constraint[6] == '}') {
24275
24276       Res.first = X86::FP0+Constraint[4]-'0';
24277       Res.second = &X86::RFP80RegClass;
24278       return Res;
24279     }
24280
24281     // GCC allows "st(0)" to be called just plain "st".
24282     if (StringRef("{st}").equals_lower(Constraint)) {
24283       Res.first = X86::FP0;
24284       Res.second = &X86::RFP80RegClass;
24285       return Res;
24286     }
24287
24288     // flags -> EFLAGS
24289     if (StringRef("{flags}").equals_lower(Constraint)) {
24290       Res.first = X86::EFLAGS;
24291       Res.second = &X86::CCRRegClass;
24292       return Res;
24293     }
24294
24295     // 'A' means EAX + EDX.
24296     if (Constraint == "A") {
24297       Res.first = X86::EAX;
24298       Res.second = &X86::GR32_ADRegClass;
24299       return Res;
24300     }
24301     return Res;
24302   }
24303
24304   // Otherwise, check to see if this is a register class of the wrong value
24305   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24306   // turn into {ax},{dx}.
24307   if (Res.second->hasType(VT))
24308     return Res;   // Correct type already, nothing to do.
24309
24310   // All of the single-register GCC register classes map their values onto
24311   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24312   // really want an 8-bit or 32-bit register, map to the appropriate register
24313   // class and return the appropriate register.
24314   if (Res.second == &X86::GR16RegClass) {
24315     if (VT == MVT::i8 || VT == MVT::i1) {
24316       unsigned DestReg = 0;
24317       switch (Res.first) {
24318       default: break;
24319       case X86::AX: DestReg = X86::AL; break;
24320       case X86::DX: DestReg = X86::DL; break;
24321       case X86::CX: DestReg = X86::CL; break;
24322       case X86::BX: DestReg = X86::BL; break;
24323       }
24324       if (DestReg) {
24325         Res.first = DestReg;
24326         Res.second = &X86::GR8RegClass;
24327       }
24328     } else if (VT == MVT::i32 || VT == MVT::f32) {
24329       unsigned DestReg = 0;
24330       switch (Res.first) {
24331       default: break;
24332       case X86::AX: DestReg = X86::EAX; break;
24333       case X86::DX: DestReg = X86::EDX; break;
24334       case X86::CX: DestReg = X86::ECX; break;
24335       case X86::BX: DestReg = X86::EBX; break;
24336       case X86::SI: DestReg = X86::ESI; break;
24337       case X86::DI: DestReg = X86::EDI; break;
24338       case X86::BP: DestReg = X86::EBP; break;
24339       case X86::SP: DestReg = X86::ESP; break;
24340       }
24341       if (DestReg) {
24342         Res.first = DestReg;
24343         Res.second = &X86::GR32RegClass;
24344       }
24345     } else if (VT == MVT::i64 || VT == MVT::f64) {
24346       unsigned DestReg = 0;
24347       switch (Res.first) {
24348       default: break;
24349       case X86::AX: DestReg = X86::RAX; break;
24350       case X86::DX: DestReg = X86::RDX; break;
24351       case X86::CX: DestReg = X86::RCX; break;
24352       case X86::BX: DestReg = X86::RBX; break;
24353       case X86::SI: DestReg = X86::RSI; break;
24354       case X86::DI: DestReg = X86::RDI; break;
24355       case X86::BP: DestReg = X86::RBP; break;
24356       case X86::SP: DestReg = X86::RSP; break;
24357       }
24358       if (DestReg) {
24359         Res.first = DestReg;
24360         Res.second = &X86::GR64RegClass;
24361       }
24362     }
24363   } else if (Res.second == &X86::FR32RegClass ||
24364              Res.second == &X86::FR64RegClass ||
24365              Res.second == &X86::VR128RegClass ||
24366              Res.second == &X86::VR256RegClass ||
24367              Res.second == &X86::FR32XRegClass ||
24368              Res.second == &X86::FR64XRegClass ||
24369              Res.second == &X86::VR128XRegClass ||
24370              Res.second == &X86::VR256XRegClass ||
24371              Res.second == &X86::VR512RegClass) {
24372     // Handle references to XMM physical registers that got mapped into the
24373     // wrong class.  This can happen with constraints like {xmm0} where the
24374     // target independent register mapper will just pick the first match it can
24375     // find, ignoring the required type.
24376
24377     if (VT == MVT::f32 || VT == MVT::i32)
24378       Res.second = &X86::FR32RegClass;
24379     else if (VT == MVT::f64 || VT == MVT::i64)
24380       Res.second = &X86::FR64RegClass;
24381     else if (X86::VR128RegClass.hasType(VT))
24382       Res.second = &X86::VR128RegClass;
24383     else if (X86::VR256RegClass.hasType(VT))
24384       Res.second = &X86::VR256RegClass;
24385     else if (X86::VR512RegClass.hasType(VT))
24386       Res.second = &X86::VR512RegClass;
24387   }
24388
24389   return Res;
24390 }
24391
24392 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24393                                             Type *Ty) const {
24394   // Scaling factors are not free at all.
24395   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24396   // will take 2 allocations in the out of order engine instead of 1
24397   // for plain addressing mode, i.e. inst (reg1).
24398   // E.g.,
24399   // vaddps (%rsi,%drx), %ymm0, %ymm1
24400   // Requires two allocations (one for the load, one for the computation)
24401   // whereas:
24402   // vaddps (%rsi), %ymm0, %ymm1
24403   // Requires just 1 allocation, i.e., freeing allocations for other operations
24404   // and having less micro operations to execute.
24405   //
24406   // For some X86 architectures, this is even worse because for instance for
24407   // stores, the complex addressing mode forces the instruction to use the
24408   // "load" ports instead of the dedicated "store" port.
24409   // E.g., on Haswell:
24410   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24411   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24412   if (isLegalAddressingMode(AM, Ty))
24413     // Scale represents reg2 * scale, thus account for 1
24414     // as soon as we use a second register.
24415     return AM.Scale != 0;
24416   return -1;
24417 }
24418
24419 bool X86TargetLowering::isTargetFTOL() const {
24420   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24421 }